After_request hooks let you run code right after your web app sends a response. This helps you change or add things to the response before it goes to the user.
Add custom headers to every response, like security or tracking info.
Log details about the response for debugging or analytics.
Modify the response content or status code before sending it.
Close or clean up resources after handling a request.
Set cookies or session data after processing a request.
This Flask app adds a security header to every response using an after_request hook. When you visit the home route, the JSON response will include the extra header.
D. The print statement is not allowed in after_request
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 C
Quick Check:
after_request functions need response param [OK]
Hint: after_request functions always take response argument [OK]
Common Mistakes:
Omitting the response parameter in after_request function
Returning a string instead of a response object
Confusing after_request with before_request
5. You want to add a security header X-Frame-Options: DENY to all responses except those from the /public route. How can you implement this using after_request hooks?
hard
A. Use before_request to add the header unconditionally
B. Use after_request to check request.path and add header only if path is not '/public'
C. Add the header inside each route function manually
D. Use after_request but always add the header regardless of path
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 accessing request.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 if request.path != '/public'.
Final Answer:
Use after_request to check request.path and add header only if path is not '/public' -> Option B
Quick Check:
Conditionally add headers in after_request using request.path [OK]
Hint: Check request.path in after_request to add headers conditionally [OK]
Common Mistakes:
Adding headers unconditionally ignoring route
Using before_request which can't modify response headers
Manually adding headers in every route instead of centralized hook
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.