0 day streak
python / expert
Snippet

Custom Django Middleware for Request Timing

Django middleware hooks into the request/response cycle, allowing you to process requests before they reach the view and modify responses before they're sent back. This expert-level middleware measures request processing time using perf_counter for high-precision timing and attaches the result as a custom header. The process_exception hook handles errors globally across all views.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import time
from django.http import JsonResponse
class TimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start = time.perf_counter()
response = self.get_response(request)
duration = time.perf_counter() - start
response['X-Request-Duration'] = f'{duration:.4f}s'
return response
def process_exception(self, request, exception):
return JsonResponse({'error': str(exception)}, status=500)
django
Breakdown
1
import time
Imports the time module for high-precision timing functions
2
class TimingMiddleware:
Defines a middleware class that follows Django's middleware pattern
3
def __init__(self, get_response):
Django calls this once when the server starts to initialize the middleware
4
def __call__(self, request):
Django invokes this for each request, passing the request object
5
start = time.perf_counter()
perf_counter provides the most accurate monotonic timer available
6
response['X-Request-Duration'] = f'{duration:.4f}s'
Attaches timing data as a custom HTTP header for monitoring