Tornado是一个轻量级完整的web框架,在Linux系统下它会使用epoll,是一个异步非阻塞的web服务器框架,对于实时应用来说很理想,想想同是异步非阻塞的nginx的残暴程度就知道了

1.路由系统

 application = tornado.web.Application([
(r'/login', LoginHandler),
(r'/index', IndexHandler),    每个url是由一个类处理的
], **settings) class IndexHandler(SessionHandler, tornado.web.RequestHandler):
def get(self):
current_user = self.session['username']
if current_user:
self.write(current_user)
else:
self.write('喵喵喵喵?')
 application = tornado.web.Application([
(r'/login', LoginHandler),
(r'/index', IndexHandler), # 处理www.bfmq.com/index
], **settings) # 二级域名
application.add_handlers('cmdb.bfmq.com', [
(r'/main', CmdbHandler),
(r'/main', MainHandler),
(r'/index', IndexHandler), # 处理cmdb.bfmq.com/index
])

2.模版引擎

与django类似,支持母板,导入,{{  }},{%  %}

 settings = {
'template_path': 'views', # 存放html模版的路径
'ui_methods': methods, # UIMethod的py文件
'ui_modules': modules, # UIModule的py文件
} class MainHandler(SessionHandler, tornado.web.RequestHandler):
def get(self):
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>
 def miao(self, a):
return '喵喵喵喵'

3.配置文件

 settings = {
'template_path': 'views', # 存放html模版的路径
'ui_methods': methods, # UIMethod的py文件
'ui_modules': modules, # UIModule的py文件
'static_path': 'statics', # 静态文件存放路径
'static_url_prefix': '/statics/', # 静态文件访问url
}

4.cookie及加密

 class IndexHandler(tornado.web.RequestHandler):
def get(self):
if not self.get_cookie("mycookie"): # 获取cookie
self.set_cookie("mycookie", "myvalue") # 设置cookie
self.write("喵喵喵喵?")
else:
self.write("喵~") class IndexHandler(tornado.web.RequestHandler):
def get(self):
if not self.get_secure_cookie("mycookie"): # 获取加密cookie
self.set_secure_cookie("mycookie", "myvalue") # 设置加密cookie
self.write("喵喵喵喵?")
else:
self.write("喵~") application = tornado.web.Application([
(r"/index", IndexHandler),
], cookie_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") # 对此应用时提供一个密钥

5.异步非阻塞

使用装饰器 + Future实现

 class AsyncHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
future = Future()
future.add_done_callback(self.doing)
yield future
# 或
# tornado.ioloop.IOLoop.current().add_future(future,self.doing)
# yield future def doing(self, *args, **kwargs):
self.write('async')
self.finish()
05-25 19:32