如何为Flask中的所有请求运行一个操作? [英] How do I run an action for all requests in Flask?
本文介绍了如何为Flask中的所有请求运行一个操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码要运行Flask的每个请求 - 特别是添加一些分析信息。我知道我可以用装饰器做到这一点,但我宁愿不浪费我的每个视图的额外的代码行。有没有办法只写这个代码的捕获所有将被应用在每个视图之前或之后?
解决方案
Flask has在请求之前和之后调用专用的钩子。令人惊讶的是,他们被称为:
-
Flask.before_request()
-
/ ul>
这两个都是装饰器:
@ app.before_request
def do_something_whenever_a_request_comes_in():
#请求可用
@ app.after_request
def do_something_whenever_a_request_has_been_handled(响应):
#我们有一个操作响应,总是返回一个
返回回应
I have some code I want to run for every request that comes into Flask-- specifically adding some analytics information. I know I could do this with a decorator, but I'd rather not waste the extra lines of code for each of my views. Is there a way to just write this code in a catch all that will be applied before or after each view?
解决方案
Flask has dedicated hooks called before and after requests. Surprisingly, they are called:
Both are decorators:
@app.before_request
def do_something_whenever_a_request_comes_in():
# request is available
@app.after_request
def do_something_whenever_a_request_has_been_handled(response):
# we have a response to manipulate, always return one
return response
这篇关于如何为Flask中的所有请求运行一个操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文