前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >初学tornado之MVC版helloworld(二)

初学tornado之MVC版helloworld(二)

作者头像
the5fire
发布2019-02-28 16:21:24
5220
发布2019-02-28 16:21:24
举报

文接上篇,看我一个简单的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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-08-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档