Python Flask: running code before and after every request

Python Flask: running code before and after every request

Learn how to run your own code before or after any Flask request using a single function allowing access and modifications of the request context and response object.


Python's Flask library is a quick and simple way of creating your own web application, it does however come with a wide range of functionality, making it a great solution to a wide range of problems.


In Flask it is possible to catch all requests in your application before or after they are processed in an endpoint, allowing you to run your code at the point it is caught. This can be extremely useful for tasks such as request altering, response altering and performance logging.


A Flask application objects comes with 2 methods- after_request() and before_request()- that can be assigned a function to run in the specified situation.


Python Flask request processing lifecycle


From both of these functions you can make use of the request context,


meaning you can access headers and other data from each request. From


the after_request() method you can access the response that was returned from the requested endpoint.


Running code before Flask requests are processed


To run your code before each Flask request, you can assign a function to the before_request() method, this can be done using decorators to make it a little simpler.


@app.before_request 
def before_request_callback(): 
    # your code here 


This function will run before each and every endpoint you have in your application. Once the code within this function has completed, the code within the actual endpoint that initiated the before_request() method will run.


In the function you created for the before_request() method, you have the opportunity to access the request object just like you would inside an endpoint, fetching or modifying any data from within the request object.


For example you could fetch the request path and method and run another function if it meets a certain criteria.


@app.before_request 
def before_request_callback(): 
    method = request.method 
    path = request.path 
         
    if path == "/" and method == "POST": 
        myfunction() 


Running code after Flask requests are processed


To run your code after each Flask request, you can assign a function to


the after_request() method using a decorator. This is done similarly to how you would run code before a request, except the after_request() method will pass the assigned function the response of the request as an argument so you must include a corresponding parameter as well as return that response at the end of the function.


@app.after_request 
def after_request_callback( response ): 
    # your code here 
    return response 


The after_request() method is a little more complicated as you can see. Not only can you access the request context, but as you receive the request response, you can also use or modify it as you like, you are however required to return that response whether or not you've modified it, as that will be the final response that the user actually receives.


The response object should be accessed using the get_data() method which will return the value that was assigned to the response object in the relevant endpoint.


@app.after_request 
def after_request_callback( response ): 
 
    response_value = response.get_data() 
    print( response_value ) 
 
    return response


To modify the value of the response object, you must make use of the set_data() method which will reset the return value the provided argument.


@app.after_request 
def after_request_callback( response ): 
       
    response_value = response.get_data() 
    print( response_value ) 
   
    response.set_data( "test" ) 
   
    response_value = response.get_data() 
    print( response_value ) 
       
    return response


If the initial value of the response object in the above example was "hello world" then you would see the following output in the console:


hello world   
test   


Full example: run code both before and after each request


In this example we will create a new flask application with 2 endpoints. Our before_request() method will read the request path and method, and print those out. Our after_request() method will print out the initial value of the response object, then modify it to include a "_changed" suffix.


from flask import Flask, request   
   
app = Flask(__name__)   
   
@app.route( "/test1" )   
def test1():   
    return "You have reached test 1"   
   
@app.route( "/test2" )   
def test2():   
    return "You have reached test 2"   
   
   
@app.after_request   
def after_request_callback(response):   
    response_value = response.get_data()   
    print( response_value )   
   
    response.set_data( response_value + "_changed" ) 
   
    response_value = response.get_data()   
    print( response_value )   
   
    return response   
   
@app.before_request   
def after_request_callback():   
    path = request.path   
    method = request.method   
   
    print( path + " [" + method + "]" )   
   
if __name__ == "__main__":   
    app.run()   


When you call the endpoint /test1 you should see the following in the console of your Flask application:


/test1 [GET]   
You have reached test 1   
You have reached test1_changed   
   


and the result of the request will be:


"You have reached test1_changed"


And when you call the endpoint /test2 you should see the following in the console of your Flask application:


/test2 [GET]   
You have reached test 2   
You have reached test2_changed   


and the result of the request will be:


"You have reached test2_changed"


If you're struggling to understand the examples above or want to ask a related question, feel free to do so in the comments below!



Christopher Thornton@Instructobit 6 years ago
or