標籤:https __file__ hand modules instance div hive 啟動 傳遞
前言: 啟動一個tornado 伺服器基本代碼
1 class HomeHandler(tornado.web.RequestHandler): #建立 RequesHandler 對象,處理接收到的 http 請求 2 def get(self): 3 entries = self.db.query("SELECT * FROM entries ORDER BY published DESC LIMIT 5") 4 if not entries: 5 self.redirect("/compose") 6 return 7 self.render("home.html", entries=entries) 8 9 class Application(tornado.web.Application): #建立 Application 對象, 定義 setting 和 URL 對應規則10 def __init__(self):11 handlers = [12 (r"/", HomeHandler),13 (r"/archive", ArchiveHandler),14 ]15 settings = dict(16 blog_title=u"Tornado Blog",17 template_path=os.path.join(os.path.dirname(__file__), "templates"),18 static_path=os.path.join(os.path.dirname(__file__), "static"),19 ui_modules={"Entry": EntryModule},20 xsrf_cookies=True,21 debug=True,22 )23 tornado.web.Application.__init__(self, handlers, **settings) #將參數設定傳遞到父類 Application中24 25 26 def main():27 http_server = tornado.httpserver.HTTPServer(Application()) #傳遞 Application 對象,封裝成 HTTPServer 對象28 http_server.listen(8000) #啟動 HTTPServer 監聽,實際上 HTTPServer 繼承自 TCPServer,是在TCPServer 中啟動 listen Socket 連接埠29 tornado.ioloop.IOLoop.instance().start() 擷取全域IOLoop 單例,啟動IOLoop 大迴圈
Tornado 高並發源碼分析之一---啟動一個web服務