python / intermediate
Snippet
Django Middleware for Request Timing
Middleware in Django sits between the web server and your views, processing every request/response. This custom middleware measures and logs the execution time of each request, adding the duration as a custom HTTP header for monitoring purposes.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import timeimport logginglogger = logging.getLogger(__name__)class RequestTimingMiddleware:def __init__(self, get_response):self.get_response = get_responsedef __call__(self, request):start_time = time.perf_counter()response = self.get_response(request)duration = time.perf_counter() - start_timelogger.info(f"{request.method} {request.path} "f"completed in {duration:.4f}s")response['X-Response-Time'] = f"{duration:.4f}s"return response
django
Breakdown
1
def __init__(self, get_response):
Middleware initialization receives the next middleware or view in the chain
2
def __call__(self, request):
This dunder method is called for every HTTP request, processing before and after the view
3
time.perf_counter()
High-resolution performance counter for accurate timing measurements
4
response['X-Response-Time'] = f"..."
Add custom header to response for client-side timing visibility