Tornado是一个轻量级完整的web框架,在Linux系统下它会使用epoll,是一个异步非阻塞的web服务器框架,对于实时应用来说很理想,想想同是异步非阻塞的nginx的残暴程度就知道了
1.路由系统
1 application = tornado.web.Application([ 2 (r'/login', LoginHandler), 3 (r'/index', IndexHandler), 每个url是由一个类处理的 4 ], **settings) 5 6 7 8 class IndexHandler(SessionHandler, tornado.web.RequestHandler): 9 def get(self): 10 current_user = self.session['username'] 11 if current_user: 12 self.write(current_user) 13 else: 14 self.write('喵喵喵喵?')
1 application = tornado.web.Application([ 2 (r'/login', LoginHandler), 3 (r'/index', IndexHandler), # 处理www.bfmq.com/index 4 ], **settings) 5 6 7 # 二级域名 8 application.add_handlers('cmdb.bfmq.com', [ 9 (r'/main', CmdbHandler), 10 (r'/main', MainHandler), 11 (r'/index', IndexHandler), # 处理cmdb.bfmq.com/index 12 ])
2.模版引擎
与django类似,支持母板,导入,{{ }},{% %}
1 settings = { 2 'template_path': 'views', # 存放html模版的路径 3 'ui_methods': methods, # UIMethod的py文件 4 'ui_modules': modules, # UIModule的py文件 5 } 6 7 8 class MainHandler(SessionHandler, tornado.web.RequestHandler): 9 def get(self): 10 self.render('main.html', li=[11, 22, 33, 44])
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>main</h1> {{ miao(1) }} {% for i in range(len(li)) %} <p>{{ i }} --- {{ li[i] }}</p> {% end %} </body> </html>
1 def miao(self, a): 2 return '喵喵喵喵'
3.配置文件
1 settings = { 2 'template_path': 'views', # 存放html模版的路径 3 'ui_methods': methods, # UIMethod的py文件 4 'ui_modules': modules, # UIModule的py文件 5 'static_path': 'statics', # 静态文件存放路径 6 'static_url_prefix': '/statics/', # 静态文件访问url 7 }
4.cookie及加密
1 class IndexHandler(tornado.web.RequestHandler): 2 def get(self): 3 if not self.get_cookie("mycookie"): # 获取cookie 4 self.set_cookie("mycookie", "myvalue") # 设置cookie 5 self.write("喵喵喵喵?") 6 else: 7 self.write("喵~") 8 9 10 class IndexHandler(tornado.web.RequestHandler): 11 def get(self): 12 if not self.get_secure_cookie("mycookie"): # 获取加密cookie 13 self.set_secure_cookie("mycookie", "myvalue") # 设置加密cookie 14 self.write("喵喵喵喵?") 15 else: 16 self.write("喵~") 17 18 19 application = tornado.web.Application([ 20 (r"/index", IndexHandler), 21 ], cookie_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") # 对此应用时提供一个密钥
5.异步非阻塞
使用装饰器 + Future实现
1 class AsyncHandler(tornado.web.RequestHandler): 2 @gen.coroutine 3 def get(self): 4 future = Future() 5 future.add_done_callback(self.doing) 6 yield future 7 # 或 8 # tornado.ioloop.IOLoop.current().add_future(future,self.doing) 9 # yield future 10 11 def doing(self, *args, **kwargs): 12 self.write('async') 13 self.finish()