Skip to content

Request Hooks (before_request)

Flask provides request hooks to run code at specific points in the request lifecycle.

Common hooks

  • @app.before_request@app.before_request
  • @app.after_request@app.after_request
  • @app.teardown_request@app.teardown_request

false


  flowchart TD
  A[Request] --> B[before_request]
  B --> C[View Function]
  C --> D[after_request]
  D --> E[Response]
  C --> F[teardown_request]
  D --> F

false

Example: add a header

@app.after_request
def add_security_headers(response):
    response.headers["X-Content-Type-Options"] = "nosniff"
    return response
@app.after_request
def add_security_headers(response):
    response.headers["X-Content-Type-Options"] = "nosniff"
    return response

Example: simple request logging

from flask import request
 
@app.before_request
def log_request():
    app.logger.info("%s %s", request.method, request.path)
from flask import request
 
@app.before_request
def log_request():
    app.logger.info("%s %s", request.method, request.path)

teardown_request

Runs even on errors.

Good for:

  • closing resources
  • cleaning up per-request state

Avoid running heavy logic here.

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did