Flask - access the request in after_request or teardown_request

Lin picture Lin · Jan 14, 2015 · Viewed 20.1k times · Source

I want to be able to access the request object before I return the response of the HTTP call. I want access to the request via "teardown_request" and "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.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

Answer

Lin picture Lin · Jan 14, 2015

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