Flask
Custom Decorators
Build decorators to gate or augment view functions.
By EZ4Code Team
decoratorsmiddleware
Code
from functools import wraps
from flask import Flask, request, jsonify, g
app = Flask(__name__)
def require_api_key(view):
@wraps(view)
def wrapped(*args, **kwargs):
key = request.headers.get("X-API-Key")
if key != "secret":
return jsonify({"error": "unauthorized"}), 401
g.api_key = key
return view(*args, **kwargs)
return wrapped
def log_call(view):
@wraps(view)
def wrapped(*args, **kwargs):
app.logger.info(f"{request.method} {request.path}")
return view(*args, **kwargs)
return wrapped
@app.route("/secure")
@require_api_key
@log_call
def secure():
return jsonify({"ok": True, "key": g.api_key})Explanation
Decorators wrap a view with functools.wraps to preserve metadata, then add behavior before or after the call. They can short-circuit by returning early, for example rejecting a missing API key, or stash data on g for the view to read. Stacking decorators runs them bottom-up when the route is invoked.
More Flask Snippets
Routing
Define routes with methods and dynamic parameters.
Request and Response
Access request data and build custom responses.
Jinja2 Templates
Render templates with context and template inheritance.
Blueprints
Organize an app into modular blueprints.
Session
Store per-user data in signed session cookies.
Error Handling
Register custom error handlers for HTTP exceptions.