Explain how Flask's before_request and after_request decorators work.
Instruction: Describe the functionality and use cases of Flask's before_request and after_request decorators.
Context: This question tests the candidate's knowledge of Flask's request handling mechanism, specifically the customization of request preprocessing and postprocessing.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
before_request runs before view dispatch. Returning a non-None response value skips the remaining normal dispatch path, so it can implement a deliberate early rejection. after_request receives and must return a response, making it suitable for bounded response-header changes.
This Flask3.1 example creates a server-generated request ID and adds it to the response:...