如何在 Tornado 中实现 Middleware
定义 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()
可以运行的例子
实现登录检查
在线统计
相关推荐
selectY 2020-07-18
zhangxuelong 2020-06-14
zhangxuelong 2020-06-14
牧码人 2020-06-14
hjhmpl 2020-06-14
thundor 2020-05-05
Cagey 2020-04-25
KarlDoenitz 2020-04-16
牧码人 2020-01-25
KarlDoenitz 2019-12-28
hjhmpl 2019-12-25
hjhmpl 2019-12-17
selectY 2019-12-11
KarlDoenitz 2019-12-06
selectY 2019-12-05
Cagey 2019-12-05
hjhmpl 2019-11-03
牧码人 2019-11-03
chenzhanhai 2019-04-09