python / expert
Snippet
Parametrized View Decorator for Dynamic Request Control Flow
Higher-order functions in Python can alter control flow before reaching Django views. By creating closure-based decorators, request execution is gated or rejected early based on custom conditions such as request headers or access tokens.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from functools import wrapsfrom django.http import HttpResponseForbidden, HttpRequestfrom typing import Callable, Anydef require_header_flag(header_name: str, expected_value: str):"""Higher-order decorator controlling view execution flow based on request headers."""def decorator(view_func: Callable[..., Any]) -> Callable[..., Any]:@wraps(view_func)def _wrapped_view(request: HttpRequest, *args: Any, **kwargs: Any):header_val = request.headers.get(header_name)if header_val != expected_value:return HttpResponseForbidden(f"Missing or invalid header: {header_name}")return view_func(request, *args, **kwargs)return _wrapped_viewreturn decorator
django
Breakdown
1
def require_header_flag(header_name: str, expected_value: str):
Outer factory function accepting parameters to customize decorator behavior.
2
def decorator(view_func: Callable[..., Any]) -> Callable[..., Any]:
Intermediate decorator accepting the target Django view function.
3
@wraps(view_func)
Preserves docstrings, function names, and metadata of the original view function.
4
if header_val != expected_value: return HttpResponseForbidden(...)
Branching control flow that halts view execution and returns an HTTP 403 response if header validation fails.