0
0
Flaskframework~3 mins

Why After_request hooks in Flask? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change every response in your app with just one simple function?

The Scenario

Imagine you have a web app where you want to add a security header or log every response manually after sending it to the user.

You have to repeat this code in every route handler, which is tiring and easy to forget.

The Problem

Manually adding code after every response is slow and error-prone.

You might miss some routes, causing inconsistent behavior and security risks.

It also clutters your route functions with repetitive tasks.

The Solution

After_request hooks let you run code automatically after every response is created.

This keeps your route code clean and ensures consistent actions like adding headers or logging.

Before vs After
Before
def route():
    response = make_response('Hello')
    response.headers['X-Security'] = 'safe'
    log_response(response)
    return response
After
@app.after_request
def add_header(response):
    response.headers['X-Security'] = 'safe'
    log_response(response)
    return response
What It Enables

You can easily add or modify response behavior globally without touching each route.

Real Life Example

Adding a security header like Content-Security-Policy to every response to protect users from attacks.

Key Takeaways

Manually modifying responses in every route is repetitive and risky.

After_request hooks run code automatically after each response.

This keeps your app consistent, clean, and secure.