python / intermediate
Snippet
Short-Circuiting Pipeline Execution in Custom Django Middleware
Django middleware controls the request processing flow. By returning a response directly from __call__ prior to calling get_response, the middleware short-circuits the pipeline and prevents downstream view execution.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.http import JsonResponseclass IpFilterMiddleware:def __init__(self, get_response):self.get_response = get_responseself.blocked_ips = {"192.168.1.100"}def __call__(self, request):client_ip = request.META.get('REMOTE_ADDR')if client_ip in self.blocked_ips:return JsonResponse({"error": "Access Denied"}, status=403)response = self.get_response(request)return response
django
Breakdown
1
def __init__(self, get_response):
Receives and stores the next request handler in the middleware chain.
2
client_ip = request.META.get('REMOTE_ADDR')
Extracts the incoming IP address from request HTTP metadata.
3
if client_ip in self.blocked_ips:
Evaluates conditional control flow to detect blocked IP addresses.
4
return JsonResponse({"error": "Access Denied"}, status=403)
Returns immediate response to halt processing without reaching view functions.