Flask - access to request in after_request or teardown_request

I want to have access to the request object before returning an HTTP call response. I want to access the request through "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 little strange. I am sure there is a better way to access the request.

thanks

+11
source share
2 answers

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 
+23
source

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

0
source

Source: https://habr.com/ru/post/980972/


All Articles