What if you could change every response in your app with just one simple function?
Why After_request hooks in Flask? - Purpose & Use Cases
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.
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.
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.
def route(): response = make_response('Hello') response.headers['X-Security'] = 'safe' log_response(response) return response
@app.after_request def add_header(response): response.headers['X-Security'] = 'safe' log_response(response) return response
You can easily add or modify response behavior globally without touching each route.
Adding a security header like Content-Security-Policy to every response to protect users from attacks.
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.