Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass arguments to after_request?

Tags:

python

flask

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
like image 944
user3287829 Avatar asked Mar 07 '14 19:03

user3287829


1 Answers

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.

like image 55
Martijn Pieters Avatar answered Sep 29 '22 15:09

Martijn Pieters