初学tornado之MVC版helloworld
?
作者:the5fire | 標簽:?MVC??tornado? | 發(fā)布:2012-08-06 2:41 p.m.文接上篇,看我一個簡單的helloworld,雖然覺得這個框架著實精小,但是實際開發(fā)總不能這么用。所以還是應(yīng)該按照實際開發(fā)來寫一個helloworld。
既然是實際項目版的helloworld,那就要有組織結(jié)構(gòu),不能代碼都塞在一個文件里。
大體結(jié)構(gòu)如下:
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結(jié)構(gòu),通過urls.py來控制訪問,通過handlers來處理所有的訪問,通過model來處理持久化的內(nèi)容。剩下的static和templates就不用說了。另外可以通過在model和handlers之間增加cache層來提升性能。
下面逐一給出實例代碼: server.py,用來啟動web服務(wù)器:
#coding:utf-8import 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:the5firefrom 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-8from handlers.index import MainHandler urls = [ (r'/', MainHandler), ]handlers/index.py:
#coding:utf-8import 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-8class 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; }大體上就這些,當然所有的東西都不是不可變的,應(yīng)該按照自己的喜好來寫。 最后運行的時候通過:python server.py 8000 代碼可以在線查看,我的github庫,有很多代碼哦:https://github.com/the5fire/practice_demo/tree/master/learn_tornado/mvc_hello
?
轉(zhuǎn)載于:https://www.cnblogs.com/DjangoBlog/p/6122832.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的初学tornado之MVC版helloworld的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .net 如何设置和检索特性信息(att
- 下一篇: 利用深度学习方法进行情感分析以及在海航舆