Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - access the request in after_request or teardown_request

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

like image 206
Lin Avatar asked Jan 14 '15 08:01

Lin


People also ask

How do I get the request context in Flask?

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.

How do you get the request object in Flask?

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.

How do I get request parameters in Flask?

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.

How does request work in Flask?

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.


1 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
like image 55
Lin Avatar answered Sep 21 '22 16:09

Lin