[英]Flask - access the request in after_request or teardown_request
I want to be able to access the request object before I return the response of the HTTP call. 我想在返回HTTP调用的响应之前能够访问请求对象。 I want access to the request via "teardown_request" and "after_request": 我希望通过“teardown_request”和“after_request”访问请求:
from flask import Flask
...
app = Flask(__name__, instance_relative_config=True)
...
@app.before_request
def before_request():
# do something
@app.after_request
def after_request(response):
# get the request object somehow
do_something_based_on_the_request_endpoint(request)
@app.teardown_request
def teardown_request(response):
# get the request object somehow
do_something_based_on_the_request_endpoint(request)
I saw that I can add the request to g and do something like this: 我看到我可以将请求添加到g并执行以下操作:
g.curr_request = request
@app.after_request
def after_request(response):
# get the request object somehow
do_something_based_on_the_request_endpoint(g.curr_request)
But the above seems a bit strange. 但上面看起来有点奇怪。 I'm sure that there's a better way to access the request. 我确信有更好的方法来访问请求。
Thanks 谢谢
The solution is simple - 解决方案很简单 -
from flask import request
@app.after_request
def after_request(response):
do_something_based_on_the_request_endpoint(request)
return response
Also try teardown_request(exception). 也尝试teardown_request(例外)。 This executes "regardless of whether there was an exception or not". 无论是否存在异常,都执行此操作。 Check the documentation: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.teardown_request 查看文档: http : //flask.pocoo.org/docs/0.12/api/#flask.Flask.teardown_request
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.