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
Flask uses the term context local for this. Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.
To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.
In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.
When the Flask application handles a request, it creates a Request object based on the environment it received from the WSGI server. Because a worker (thread, process, or coroutine depending on the server) handles only one request at a time, the request data can be considered global to that worker during that request.
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
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