0
0
FlaskHow-ToBeginner · 3 min read

How to Use before_request in Flask for Preprocessing Requests

In Flask, use the @app.before_request decorator to register a function that runs before every request. This function can perform tasks like checking user authentication or setting up variables before the main route code runs.
📐

Syntax

The @app.before_request decorator registers a function that Flask runs before each request. The function takes no arguments and can return a response to stop further processing.

  • @app.before_request: Decorator to mark the function.
  • Function with no parameters: Runs before every request.
  • Optional return value: If it returns a response, Flask sends it immediately, skipping the route handler.
python
from flask import Flask

app = Flask(__name__)

@app.before_request
def before():
    # Code here runs before each request
    pass
💻

Example

This example shows how to use @app.before_request to check if a user is logged in before allowing access to routes. If not logged in, it returns a message immediately.

python
from flask import Flask, request

app = Flask(__name__)

@app.before_request
def check_auth():
    # Simple check for a query parameter 'token'
    token = request.args.get('token')
    if token != 'secret':
        return 'Unauthorized: Missing or wrong token', 401

@app.route('/')
def home():
    return 'Welcome to the protected home page!'

if __name__ == '__main__':
    app.run(debug=True)
Output
When accessing http://localhost:5000/?token=secret, the page shows: Welcome to the protected home page! When accessing without token or wrong token, it shows: Unauthorized: Missing or wrong token (HTTP 401)
⚠️

Common Pitfalls

  • Returning a response inside the before_request function stops the request and skips the route handler, which is intended but can confuse beginners.
  • Not using before_request for tasks that should run only on specific routes; it runs before every request.
  • Modifying global state without care can cause unexpected behavior since it runs on every request.
python
from flask import Flask

app = Flask(__name__)

# Wrong: returning None explicitly does nothing, but returning a response stops processing
@app.before_request
def wrong_return():
    return None  # This is ignored, request continues

# Right: return a response only when you want to stop processing
@app.before_request
def correct_return():
    # Example condition
    if False:
        return 'Stop here', 403
📊

Quick Reference

Use @app.before_request to run code before every request. Return a response to stop processing. Use it for authentication, logging, or setup tasks.

FeatureDescription
Decorator@app.before_request
Function ArgsNone (no parameters)
Return ValueOptional response to stop request
Runs BeforeEvery request to the app
Common UsesAuthentication, logging, setup

Key Takeaways

Use @app.before_request to run code before every Flask request.
Return a response in before_request to stop further request handling.
before_request functions take no arguments and run on all routes.
Ideal for tasks like authentication checks and logging.
Avoid heavy processing or global state changes that affect all requests.