tornado在RequestHandler中提供了 prepare和finish这样的方法。prepare在框架调用get/post/...这些方法之前调用。finish在最终写回response时由框架调用。所以可以利用这个实现类似 django中middleware的功能。比如登录检查,权限验证,修改response的结果都可以在middleware中完成。
class Middleware(object):
def process_request(self, handler):
pass
def process_response(self, handler):
pass
def prepare(self):
for middle in self.application.middleware:
middle.process_request(self)
super(MyRequestHandler, self).prepare()
def finish(self):
for middle in self.application.middleware:
middle.process_response(self)