初学tornado之MVC版helloworld

本文介绍使用Tornado框架实现MVC架构的Hello World应用,详细展示了项目结构与代码实现,包括server启动、settings配置、URL路由、handler处理、model持久化及模板渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

作者:the5fire | 标签:  MVC   tornado  | 发布:2012-08-06 2:41 p.m.

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

/**
author:the5fire
**/

body {
background-color:#ccc;
}

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值