the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


初学tornado之MVC版helloworld(二)

作者:the5fire | 标签:     | 发布:2012-08-06 10:41 p.m. | 阅读量: 21202, 20522

文接上篇,看我一个简单的helloworld,虽然觉得这个框架着实精小,但是实际开发总不能这么用。所以还是应该按照实际开发来写一个helloworld。

既然是实际项目版的helloworld,那就要有组织结构,不能代码都塞在一个文件里。

大体结构如下:

mvc_helloworld
    --__init__.py
    --urls.py
    --application.py
    --server.py
    --handlers
        --__init__.py
        --index.py
    --model
        --__init__.py
        --entity.py
    --static
        --css
            --index.css
        --js
        --img
    --templates
        --index.html

这是一个简单的mvc结构,通过urls.py来控制访问,通过handlers来处理所有的访问,通过model来处理持久化的内容。剩下的static和templates就不用说了。另外可以通过在model和handlers之间增加cache层来提升性能。

下面逐一给出实例代码: server.py,用来启动web服务器:

#coding:utf-8

import tornado.ioloop
import sys

from application import application

PORT = '8080'

if __name__ == "__main__":
    if len(sys.argv) > 1:
        PORT = sys.argv[1]

    application.listen(PORT)
    print 'Development server is running at http://127.0.0.1:%s/' % PORT
    print 'Quit the server with CONTROL-C'
    tornado.ioloop.IOLoop.instance().start()

application.py,可以作为settings:

#coding:utf-8
#author:the5fire

from urls import urls

import tornado.web
import os
SETTINGS = dict(
    template_path=os.path.join(os.path.dirname(__file__), "templates"),
    static_path=os.path.join(os.path.dirname(__file__), "static"),
)

application = tornado.web.Application(
    handlers = urls,
    **SETTINGS
)

urls.py:

#coding:utf-8

from handlers.index import MainHandler

urls = [
    (r'/', MainHandler),
]

handlers/index.py:

#coding:utf-8

import tornado.web
from model.entity import Entity

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        entity = Entity.get('the5fire\'s blog')
        self.render('index.html', entity = entity)

model/entity.py:

#coding:utf-8

class Entity(object):
    def __init__(self, name):
        self.name = name

    @staticmethod
    def get(name):
        return Entity(name)

templates/index.html:

<!DOCYTYPE html>
<html>
<head>
    <meta type="utf-8">
    <title>首页</title>
    <link href="/static/css/index.css" media="screen" rel="stylesheet" type="text/css"/>
</head>
<body>
    <h1>Hello, tornado World!</h1>
    <h2>by <a href="http://www.the5fire.com" target="_blank">{{entity.name}}</a></h2>
</body>
</html>

static/css/index.css:

.. code:: html

/**
author:the5fire
**/

body {
background-color:#ccc;
}

大体上就这些,当然所有的东西都不是不可变的,应该按照自己的喜好来写。 最后运行的时候通过:python server.py 8000 代码可以在线查看,我的github库,有很多代码哦:https://github.com/the5fire/practice_demo/tree/master/learn_tornado/mvc_hello

- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: