python / intermediate
Snippet
Custom Rate Limiting Middleware Using Django Cache System
Django middleware intercepts incoming HTTP requests before view execution. By leveraging Django's low-level cache API inside a middleware __call__ method, IP address request frequencies can be monitored and throttled dynamically to enhance endpoint security.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.core.cache import cachefrom django.http import HttpResponseTooManyRequestsclass SimpleRateLimitMiddleware:def __init__(self, get_response):self.get_response = get_responsedef __call__(self, request):client_ip = request.META.get('REMOTE_ADDR', '127.0.0.1')cache_key = f"rl_count:{client_ip}"request_count = cache.get(cache_key, 0)if request_count >= 100:return HttpResponseTooManyRequests("Rate limit exceeded. Try again in 60 seconds.")cache.set(cache_key, request_count + 1, timeout=60)return self.get_response(request)
django
Breakdown
1
def __init__(self, get_response):
Initializes the middleware instance once when the web server starts, accepting the next handler.
2
client_ip = request.META.get('REMOTE_ADDR', '127.0.0.1')
Extracts the client IP address from the request headers to construct a unique cache key.
3
if request_count >= 100:
Checks if the threshold for maximum allowed requests within the time window has been breached.
4
cache.set(cache_key, request_count + 1, timeout=60)
Increments counter in cache storage with an expiration period of 60 seconds.