I am new to Flask and am learning about the @app.after_request
and @app.teardown_appcontext
. I have a decorated view for oauthlib that takes an argument, data
(which is an object).
@app.route('/api/me')
@oauth.require_oauth()
def me(data):
user = data.user
return jsonify(username=user.username)
After this view (and many other views) are executed, I'd like to update my database but need to have access to the variable data
. How do I do that with @app.after_request
or @app.teardown_appcontext
?
@app.after_request
def record_ip(response):
client = data.client # needs access to "data"
.... log stuff in my database ...
return response
You can add the object to the flask.g
globals object:
from flask import g
@app.route('/api/me')
@oauth.require_oauth()
def me(req):
user = req.user
g.oauth_request = req
return jsonify(username=user.username)
@app.after_request
def record_ip(response):
req = g.get('oauth_request')
if req is not None:
client = req.client # needs access to "req"
# .... log stuff in my database ...
return response
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.
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