如何在 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

  1. 可以在 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()

可以运行的例子

  1. 实现登录检查

  2. 在线统计

https://gist.github.com/alex8224/7e4ca9a27727cf2a86b6

相关推荐