22

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

Lin
  • 2,445
  • 5
  • 27
  • 37
  • Could you clarify your question a little bit by: 1) Adding the relevant import statements 2) What do you mean with "I want access via "teardown_request" and "after_request":" – joostdevries Jan 14 '15 at 08:55
  • @joostdevries - I edited the question. I want to do some operations based on the original request before sending the response (in my case I need to handle some things related to the db transactions based on the request URL...), but I'm not sure how to access the request in "after_request" and "teardown_request" – Lin Jan 14 '15 at 09:01
  • What's wrong with using g to keep a reference to the request, or maybe better, just the url or the relevant part of the url? Given the pattern recommended here to do the opposite of what you want (modify the response in the before_request() method), using g seems like a simple and reasonable solution: http://flask.pocoo.org/docs/0.10/patterns/deferredcallbacks/ – bsa Jan 14 '15 at 09:16
  • I thought that there's a better way, but I can absolutely use g. – Lin Jan 14 '15 at 09:27
  • Actually - I debugged again and saw that I actually do have the request in the teardown/after_request bu using: from flask import request – Lin Jan 14 '15 at 09:30

2 Answers2

36

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
André C. Andersen
  • 8,955
  • 3
  • 53
  • 79
Lin
  • 2,445
  • 5
  • 27
  • 37
0

Also try teardown_request(exception). This executes "regardless of whether there was an exception or not". Check the documentation: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.teardown_request

Ahmad sibai
  • 147
  • 2
  • 4