Tornado之初學者(二),tornado初學者
三、tornado.web.Application
1、Application:tornado.web.Aplication建立一個應用,可通過直接執行個體化這個類或執行個體化它的子類來建立應用;
2、handlers:執行個體化時至少需要傳入參數handlers,handlers為元素為元組的列表,元組中第一個元素為路由,第二個元素為路由對應的RequestHandler處理類;路由為Regex,當Regex中有分組時,訪問時會將分組的結果當做參數傳入模板中;
3、settings:還有一個執行個體化時經常用到的參數settings,這個參數是一個字典:
①template_path:設定模板檔案(HTML檔案);
②static_path:設定靜態檔案(像、CSS檔案、JavaScript檔案等)的路徑;
③debug:設定成True時開啟偵錯模式,tornado會調用tornado.autoreload模組,當Python檔案被修改時,會嘗試重新啟動伺服器並在模板改變時重新整理瀏覽器(在開發時使用,不要在生產中使用);
④ui_modules:設定自訂UI模組,傳入一個模組名(變數名)為鍵、類為值的字典,這個類為tornado.web.UIModule的子類,在HTML中使用{% module module_name %}時會自動包含module_name類中render方法返回的字串(一般為包含HTML標籤內容的字串),如果是HTML檔案,返回的就是HTML模板中內容的字串。
4、資料庫:可以在Application的子類中串連資料庫“self.db = database”,然後在每個RequestHandler中都可以使用串連的資料庫“db_name = self.application.db.database”。
1 # 定義了模板路徑和靜態檔案路徑後,在使用到模板和靜態檔案的地方就不需要逐一添加和修改了 2 settings = { 3 'template_path': os.path.join(os.path.dirname(__file__), 'templates'), 4 'static_path': os.path.join(os.path.dirname(__file__), 'static'), 5 'debug': True, 6 } 7 8 # 對應的RequestHandler類代碼未貼出來 9 app = tornado.web.Application(10 handlers=[(r'/',MainHandler),
11 (r'/home', HomePageHandler),
12 (r'/demo/([0-9Xx\-]+)', DemoHandler), # 有分組時會將分組結果當參數傳入對應的模板中
13 ],
14 **settings
15 )
1 class Application(tornado.web.Application): 2 def __init__(self): 3 handlers = [ 4 (r'/', MainHandler), 5 (r'/demo/([0-9Xx\-]+)', DemoHandler), 6 ] 7 8 settings = dict( 9 template_path=os.path.join(os.path.dirname(__file__), 'templates'),10 static_path=os.path.join(os.path.dirname(__file__), 'static'),11 ui_modules={'Mymodule': Mymodule},12 debug=True,13 )14 15 # 這裡使用的資料庫是MongoDB,Python有對應的三方庫pymongo作為驅動來串連MongoDB資料庫16 conn = pymongo.MongoClient()17 self.db = conn['demo_db']18 tornado.web.Application.__init__(self, handlers, **settings)19 20 class DemoHandler(tornado.web.RequestHandler):21 def get(self):22 demo_db = self.application.db.demo_db # 直接使用串連的資料庫23 sets = demo_db.find()24 self.render(25 'demo.html',26 sets=sets,27 )28 29 class Mymodule(tornado.web.UIModule):30 def render(self):31 return self.render_string('modules/mod.html',)32 33 # 定義css檔案路徑34 def css_files(self):35 return '/static/css/style.css'36 37 # 定義js檔案路徑38 def javascript_files(self):39 return '/static/js/jquery-3.2.1.js'