before_request / Request Hooks (Flask)
before_request is a Flask hook that runs a function before every request is dispatched to a view. With siblings after_request and teardown_request, these hooks let you run setup and cleanup code around all of your views.
Flask
Request hooks centralize cross-cutting concerns. @app.before_request runs first and can do things like open a database connection, load the current user onto g, or short-circuit by returning a response (for example to force login or maintenance mode).
@app.after_request receives the response and can modify it — adding headers, logging, or setting cookies — and must return the response. @app.teardown_request runs even if an error occurred, making it the right place to close resources.
Returning a value from a before_request handler skips the view entirely and sends that value as the response, which is how you implement gates like 'redirect everyone to /login if not authenticated'.
Syntax
@app.before_request
def hook(): ...Examples
Python
@app.before_request
def require_login():
if not session.get("user") and request.endpoint != "login":
return redirect(url_for("login"))
@app.after_request
def add_header(resp):
resp.headers["X-App"] = "demo"
return resp