Request Hooks in Python

From the Flask cheat sheet ยท Middleware & Hooks ยท verified Jul 2026

Request Hooks

Execute code before and after requests

python
# Quick Reference
@app.before_request
def before():
    g.start_time = time.time()

@app.after_request
def after(response):
    response.headers['X-Time'] = time.time() - g.start_time
    return response
๐Ÿ’ก Use g object to store request-scoped data
๐Ÿ” before_request can return early to abort request
โšก after_request modifies all responses
๐Ÿ“Œ teardown runs even if exception occurs
middlewarehooks

Continue with Flask

Save the full cheat sheet or work through every related task.

Back to the full Flask cheat sheet