Flask - 在 after_request 或 teardown_request 中访问请求
Flask - access the request in after_request or teardown_request
我希望能够在 return HTTP 调用的响应之前访问请求对象。
我想通过 "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)
我看到我可以将请求添加到 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)
不过上面的好像有点奇怪。我确信有更好的方法来访问请求。
谢谢
解决方法很简单 -
from flask import request
@app.after_request
def after_request(response):
do_something_based_on_the_request_endpoint(request)
return response
也尝试 teardown_request(例外)。这将执行 "regardless of whether there was an exception or not"。查看文档:http://flask.pocoo.org/docs/0.12/api/#flask.Flask.teardown_request
我希望能够在 return HTTP 调用的响应之前访问请求对象。 我想通过 "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)
我看到我可以将请求添加到 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)
不过上面的好像有点奇怪。我确信有更好的方法来访问请求。
谢谢
解决方法很简单 -
from flask import request
@app.after_request
def after_request(response):
do_something_based_on_the_request_endpoint(request)
return response
也尝试 teardown_request(例外)。这将执行 "regardless of whether there was an exception or not"。查看文档:http://flask.pocoo.org/docs/0.12/api/#flask.Flask.teardown_request