Django (Python)
For Django applications, the most secure way to enforce IP validation is by creating a custom middleware class. This ensures that malicious traffic is rejected before it ever reaches your Django views or consumes database connections.
The Middleware
This middleware safely determines the client’s real IP, uses the standard requests library to query ProxyTracer, and returns a raw HttpResponseForbidden to stop the request lifecycle immediately.
import os
import requests
from django.http import HttpResponseForbidden
class ProxyTracerMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.api_key = os.environ.get("PROXYTRACER_API_KEY")
def get_client_ip(self, request):
# 1. Safely extract the real IP behind load balancers/NGINX
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def __call__(self, request):
ip = self.get_client_ip(request)
# Skip local development IPs
if ip and ip not in ['127.0.0.1', '::1']:
try:
# 2. Query ProxyTracer API with a strict timeout
response = requests.get(
f"https://api.proxytracer.com/v1/check/{ip}",
headers={"Authorization": f"Bearer {self.api_key}"},
timeout=0.5 # Strict 500ms timeout to prevent bottlenecks
)
if response.status_code == 200:
data = response.json()
# 3. Drop the connection if a proxy/VPN is detected
if data.get("proxy") is True:
return HttpResponseForbidden(
'{"error": "Access Denied: VPN or Proxy detected."}',
content_type="application/json"
)
except requests.RequestException as e:
# Fail open: Log the error and allow the request through
print(f"ProxyTracer validation failed: {e}")
# 4. Traffic is clean, proceed to the view
response = self.get_response(request)
return responseConfiguration
To activate the protection, register the middleware in your settings.py file. Place it high up in the stack (right after security and session middlewares) to drop bad traffic early.
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# ...
'your_app.middleware.ProxyTracerMiddleware',
# ...
]Last updated on