Category: python
middleware hooks and request lifecycle
Published on 30 Sep 2026
Explanation
Flask hooks allow code to run at specific stages of the request lifecycle.
Code:
Request ↓ before_request ↓ Route Function ↓ after_request ↓ Response
Explanation
before_request runs before the matched route function and can be used for authentication or request preparation.
Code:
@app.before_request
def before_request():
print('Request started')
Explanation
after_request runs after the route function and can modify the response before it is returned.
Code:
@app.after_request
def after_request(response):
response.headers['X-App'] = 'Flask'
return response
Explanation
teardown_request runs when request processing is complete and is useful for cleanup operations.
Code:
@app.teardown_request
def teardown_request(exception):
print('Request completed')
Explanation
The complete Flask request lifecycle passes through request creation, hooks, routing, view execution, response processing, and teardown.
Code:
HTTP Request
↓
before_request
↓
Routing
↓
View Function
↓
after_request
↓
HTTP Response
↓
teardown_request