Tornado Application的實現(xiàn)
Application
-settings
我們在創(chuàng)建tornado.web.Application的對象時,傳入了第一個參數(shù)——路由映射列表。實際上Application類的構造函數(shù)還接收很多關于tornado web應用的配置參數(shù)。
我們先來看一個參數(shù):
debug,設置tornado是否工作在調(diào)試模式,默認為False即工作在生產(chǎn)模式。當設置debug=True 后,tornado會工作在調(diào)試/開發(fā)模式,在此種模式下,tornado為方便我們開發(fā)而提供了幾種特性:
- 自動重啟,tornado應用會監(jiān)控我們的源代碼文件,當有改動保存后便會重啟程序,這可以減少我們手動重啟程序的次數(shù)。需要注意的是,一旦我們保存的更改有錯誤,自動重啟會導致程序報錯而退出,從而需要我們保存修正錯誤后手動啟動程序。這一特性也可單獨通過autoreload=True設置;
- 取消緩存編譯的模板,可以單獨通過compiled_template_cache=False來設置;
- 取消緩存靜態(tài)文件hash值,可以單獨通過static_hash_cache=False來設置;
- 提供追蹤信息,當RequestHandler或者其子類拋出一個異常而未被捕獲后,會生成一個包含追蹤信息的頁面,可以單獨通過serve_traceback=True來設置。
使用debug參數(shù)的方法:
import tornado.web app = tornado.web.Application([], debug=True)
-路由映射
先前我們在構建路由映射列表的時候,使用的是二元元組,如:
[(r"/", IndexHandler),]
對于這個映射列表中的路由,實際上還可以傳入多個信息,如:
[
(r"/", Indexhandler),
(r"/cpp", ItcastHandler, {"subject":"c++"}),
url(r"/python", ItcastHandler, {"subject":"python"}, name="python_url")
]對于路由中的字典,會傳入到對應的RequestHandler的initialize()方法中:
from tornado.web import RequestHandler
class ItcastHandler(RequestHandler):
def initialize(self, subject):
self.subject = subject
def get(self):
self.write(self.subject)對于路由中的name字段,注意此時不能再使用元組,而應使用tornado.web.url來構建。name是給該路由起一個名字,可以通過調(diào)用RequestHandler.reverse_url(name)來獲取該名子對應的url。
# coding:utf-8
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
from tornado.options import options, define
from tornado.web import url, RequestHandler
define("port", default=8000, type=int, help="run server on the given port.")
class IndexHandler(RequestHandler):
def get(self):
python_url = self.reverse_url("python_url")
self.write('<a href="%s" rel="external nofollow" >itcast</a>' %
python_url)
class ItcastHandler(RequestHandler):
def initialize(self, subject):
self.subject = subject
def get(self):
self.write(self.subject)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application([
(r"/", Indexhandler),
(r"/cpp", ItcastHandler, {"subject":"c++"}),
url(r"/python", ItcastHandler, {"subject":"python"}, name="python_url")
],
debug = True)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()到此這篇關于Tornado Application的實現(xiàn)的文章就介紹到這了,更多相關Tornado Application內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python構造函數(shù)與析構函數(shù)超詳細分析
在python之中定義一個類的時候會在類中創(chuàng)建一個名為__init__的函數(shù),這個函數(shù)就叫做構造函數(shù)。它的作用就是在實例化類的時候去自動的定義一些屬性和方法的值,而析構函數(shù)恰恰是一個和它相反的函數(shù),這篇文章主要介紹了Python構造函數(shù)與析構函數(shù)2022-11-11
Python解析命令行讀取參數(shù)--argparse模塊使用方法
這篇文章主要介紹了Python解析命令行讀取參數(shù)--argparse模塊使用方法,需要的朋友可以參考下2018-01-01
Python創(chuàng)建類的方法及成員訪問的相關知識總結
今天給大家?guī)淼氖顷P于Python基礎的相關知識,文章圍繞著Python類的方法及成員訪問展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06
對Python 窗體(tkinter)文本編輯器(Text)詳解
今天小編就為大家分享一篇對Python 窗體(tkinter)文本編輯器(Text)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10

