Tornado 基礎安裝及啟動
Tornado 基礎安裝及啟動
2017年03月24日 hairui Tornado 115 0
Tornado的安裝
Python 2.7.x 安裝學習
手動安裝: 下載 tornado-1.2.1.tar.gz
Bashtar xvzf tornado-1.2.1.tar.gzcd tornado-1.2.1python setup.py buildsudo python setup.py install
#本段代碼來自 海瑞博客http://www.hairuinet.com/Tornado/201703102/index.html
Python 3.x安裝學習
pip3 install tornado
#本段代碼來自 海瑞博客http://www.hairuinet.com/Tornado/201703102/index.html
默認安裝為最新版本,如果指定版本可以 tornado==1.2.1 加版本號指定
Tornado的格式
Hello world
#!/usr/bin/env python# -*- coding=utf-8 -*-# blog:www.hairuinet.com# Version: 1.0__author__ = "HaiRui"import tornado.ioloopimport tornado.webclass MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world")application = tornado.web.Application([ (r"/", MainHandler),])if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
#本段代碼來自 海瑞博客http://www.hairuinet.com/Tornado/201703102/index.html
URL的配置
application = tornado.web.Application([
(r"/login.html", LoginHandler),
(r"/index.html", MainHandler),
(r"/", LoginHandler),
])
默認值匹配到信息後直接找到後面類執行對應的方法。
application.add_handlers(‘www.hairuineit.com‘,[
(r"/login.html", LoginHandler),
(r"/index.html", MainHandler),
])
可以有前綴的話,可以處理必須以 www.hairuineit.com開頭的url 再匹配裏的內容,用於多域名的情況
模板配置
settings = {
‘template_path‘: ‘templates‘,#模板地址
‘static_path‘: ‘static‘,#文件路徑
‘static_url_prefix‘: ‘static‘,#靜態文件路徑名稱
}
寫完必須傳入url內
application = tornado.web.Application([
(r"/login.html", LoginHandler),
(r"/index.html", MainHandler),
(r"/", LoginHandler),
],**settings)
編寫邏輯
Pythonclass LoginHandler(tornado.web.RequestHandler):
def get(self):
name = ‘Hairui‘
self.render("index.html",**{‘name‘:name})#渲染
#相當於django裏面的return返回的render
def post(self, *args, **kwargs):
v = self.get_argument(‘username‘)
print(v)
self.redirect(‘/index.html‘)
#本段代碼來自 海瑞博客http://www.hairuinet.com/Tornado/201703102/index.html
前臺
Markup<h3>{{name}}</h3>
#本段代碼來自 海瑞博客http://www.hairuinet.com/Tornado/201703102/index.html
Tornado 基礎安裝及啟動