Tornado:有请求过滤器吗?

2024-04-29 10:13:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在看一个Tornado应用程序,想知道如何让它执行我的用例。我需要在发送到URL处理程序之前拦截每个请求,并可能返回重定向。有没有办法用龙卷风做到这一点?在

我想知道Tornado是否有类似servlet过滤器的概念。看起来input modifierdecode_argument可能会这样做?使用这种方法过滤请求似乎有点麻烦,但我在文档中没有发现其他内容。在


Tags: 方法文档应用程序概念url处理程序过滤器input
2条回答

你至少有三种选择:

  • 使用RequestHandler.prepare()作为kamushin said

  • 正如this tornado issue comment中所说:

    You can hook up middleware, actually. HTTPServer request handlers are just callable objects (function, methods, or objects that implement __call__). You can write your own handler that passes on requests to your Application

(示例)

my_app = tornado.web.Application(...)

def middleware(request):
    # do whatever transformation you want here
    my_app(request)

if __name__ == '__main__':
    http_server = tornado.httpserver.HTTPServer(middleware)
    # ...

但请注意:

Since Tornado request handling can be asynchronous, you can't modify the response in your middleware, but you can at least work with the request.

  • 使用装饰工。有关如何实现它的详细信息,请参见this exaemple

  • 尝试一下tornado-middlewaretmiddleware。小心点,因为他们3岁了,可能不工作。但是你总是可以看看他们的代码并从中学习。

相关问题 更多 >