Request Hooks (before_request)
Flask provides request hooks to run code at specific points in the request lifecycle.
Common hooks
Section titled “Common hooks”@app.before_request@app.after_request@app.teardown_request
flowchart TD A[Request] --> B[before_request] B --> C[View Function] C --> D[after_request] D --> E[Response] C --> F[teardown_request] D --> F
Example: add a header
Section titled “Example: add a header”@app.after_request
def add_security_headers(response):
response.headers["X-Content-Type-Options"] = "nosniff"
return responseExample: simple request logging
Section titled “Example: simple request logging”from flask import request
@app.before_request
def log_request():
app.logger.info("%s %s", request.method, request.path)teardown_request
Section titled “teardown_request”Runs even on errors.
Good for:
- closing resources
- cleaning up per-request state
Avoid running heavy logic here.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading