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

阅读 4.7k

人生苦短,我用Python
专注Python,云计算

人生苦短,我用Python

127 声望
3 粉丝
0 条评论
你知道吗?

人生苦短,我用Python

127 声望
3 粉丝
文章目录
宣传栏