python / intermediate
Snippet
Django Custom Middleware for Request/Response Processing
Middleware in Django acts as a bridge between the web server and your application. Each middleware class wraps the view and can intercept requests before they reach the view and responses before they return to the client. Custom middleware is powerful for cross-cutting concerns like logging, rate limiting, authentication checks, and request modification.
snippet.py
1
from django.http import JsonResponse\n\nclass RequestLoggingMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n print(f"Request path: {request.path}")\n response = self.get_response(request)\n print(f"Response status: {response.status_code}")\n return response\n\nclass ApiRateLimitMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n if request.path.startswith('/api/'):\n client_ip = request.META.get('REMOTE_ADDR')\n if not self._check_rate_limit(client_ip):\n return JsonResponse({'error': 'Rate limit exceeded'}, status=429)\n return self.get_response(request)\n\n def _check_rate_limit(self, ip):\n return True
django
Breakdown
1
class RequestLoggingMiddleware:
Define a custom middleware class
2
def __init__(self, get_response):
Initialize with the next middleware or view in chain
3
def __call__(self, request):
Process request before view and response after view
4
if request.path.startswith('/api/'):
Filter requests by path pattern
5
return JsonResponse({'error': 'Rate limit exceeded'}, status=429)
Return early with error response when rate limit exceeded