定义 Middleware
class MiddleWare(object):
def process_request(self, request):
#request是一个RequestHandler的实例
pass
def process_response(self, request):
pass
实现登录检查 Middleware
class AuthorizationException(Exception):
def __init__(self, msg):
super(AuthorizationException, self).__init__(403, msg)
class CheckLogin(MiddleWare):
def is_login(self, requesthandler):
return True
def process_request(self, request):
if must_login(request):
if not self.is_login(request):
raise AuthenticationException(403, "login required")
def is_login(self, request):
return request.get_session() != None
找地方注册 Middleware
可以在 Tornado 初始化的时候将Middleware注册到 Application 中
调用 Middlware
class MiddleRequestHandler(RequestHandler):
def prepare(self):
for middleware in self.app.middleware:
middleware.process_request(self)
def finish(self):
for middleware in self.app.middleware:
middleware.process_response(self)
super(MiddleRequestHandler, self).finish()
可以运行的例子
实现登录检查
在线统计
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。