I want to store a value that is bound to a Flask request, I want the value to live only as long at the request and it should be availablbe in @app.after_request, how would the get_my_request_var and set_my_request_var be implemented in the code below ?
@app.route("/aRoute")
def a_function():
set_my_request_var('aName', request, 123)
@app.after_request
def per_request_callbacks(response):
v = get_my_request_var('aName', request)
return response
I'd set a value on the flask.g
globals object and retrieve that in the after_request
handler:
def set_my_request_var(name, value):
if 'my_request_var' not in g:
g.my_request_var = {}
g.my_request_var[name] = value
@app.after_request
def per_request_callbacks(response):
values = g.get('my_request_var', {})
v = values.pop('aName')
return response
@app.route("/aRoute")
def a_function():
set_my_request_var('aName', 123)
The values.pop()
removes the key from the my_request_var
dictionary on the global flask.g
context, so that a future request won't have to handle it.
The global flask.g
context is thread safe and tied to the current request; quoting from the documentation:
The application context is created and destroyed as necessary. It never moves between threads and it will not be shared between requests.
Another option is to not handle this in a after_request
handler. Use the newer @flask.after_this_request()
decorator instead to register a callback for just this request:
from flask import after_this_request
@app.route("/aRoute")
def a_function():
aName = 123
@after_this_request
def this_request_callback(response)
# do something with `aName` here
return response
or, in a helper function:
def something_after_this_request(aName):
@after_this_request
def this_request_callback(response)
# do something with `aName` here
return response
@app.route("/aRoute")
def a_function():
something_after_this_request(123)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With