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.
Practice
after_request hook in Flask?Solution
Step 1: Understand the role of after_request hooks
After_request hooks run after the view function but before the response is sent to the client.Step 2: Identify what after_request hooks modify
They receive the response object and can modify it, such as adding headers or logging.Final Answer:
To modify the response before it is sent to the client -> Option DQuick Check:
After_request hooks modify response [OK]
- Confusing after_request with before_request hooks
- Thinking after_request handles incoming data
- Assuming after_request defines routes
after_request hook in Flask?Solution
Step 1: Identify the correct decorator for after_request
The correct decorator is@app.after_requestto register a function that modifies the response.Step 2: Check function signature
The function must accept one argument (the response) and return it.Final Answer:
@app.after_request\ndef modify_response(response):\n return response -> Option AQuick Check:
Use @app.after_request with response param [OK]
- Using @app.before_request instead of after_request
- Missing the response parameter in the function
- Using a non-existent decorator like @app.after_response
from flask import Flask, Response
app = Flask(__name__)
@app.after_request
def add_header(response):
response.headers['X-Custom'] = 'Hello'
return response
@app.route('/')
def index():
return Response('OK')Solution
Step 1: Understand after_request modifies response headers
The after_request function adds a header 'X-Custom' with value 'Hello' to the response.Step 2: Check the response returned by the route
The route returns a Response with body 'OK' but no custom headers initially.Step 3: Confirm header addition
The after_request hook adds the header before sending, so the final response includes 'X-Custom: Hello'.Final Answer:
Response with header 'X-Custom' set to 'Hello' -> Option AQuick Check:
after_request adds headers to response [OK]
- Thinking headers cannot be changed after response creation
- Confusing response body with headers
- Assuming after_request runs before route
from flask import Flask
app = Flask(__name__)
@app.after_request
def fix_response():
print('Fixing response')
return 'Fixed'Solution
Step 1: Check function signature for after_request
Functions registered with @app.after_request must accept one argument: the response object.Step 2: Analyze the return value
The function returns a string instead of a response object, which is incorrect.Step 3: Identify the main error
Missing the response parameter causes Flask to raise an error because it expects the response argument.Final Answer:
The function must accept a response parameter -> Option CQuick Check:
after_request functions need response param [OK]
- Omitting the response parameter in after_request function
- Returning a string instead of a response object
- Confusing after_request with before_request
X-Frame-Options: DENY to all responses except those from the /public route. How can you implement this using after_request hooks?Solution
Step 1: Use after_request to modify all responses
after_request hooks run after every request and can modify the response before sending.Step 2: Check the request path inside after_request
By accessingrequest.path, you can conditionally add headers only when the path is not '/public'.Step 3: Implement conditional header addition
Inside the after_request function, add the header only ifrequest.path != '/public'.Final Answer:
Use after_request to checkrequest.pathand add header only if path is not '/public' -> Option BQuick Check:
Conditionally add headers in after_request using request.path [OK]
- Adding headers unconditionally ignoring route
- Using before_request which can't modify response headers
- Manually adding headers in every route instead of centralized hook
Ready to prove it?
Pass the test and this pattern moves unknown
