python / intermediate
Snippet
View Access Control with Custom Function Decorators and Cache Counters
Protecting sensitive Django view endpoints against brute-force attacks or abuse can be accomplished by writing custom function decorators. Utilizing Django's caching framework inside decorator functions allows tracking and restricting per-IP request frequency dynamically with minimal latency.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from functools import wrapsfrom django.core.cache import cachefrom django.http import HttpResponseForbiddendef rate_limit_ip(max_requests=5, timeout=60):def decorator(view_func):@wraps(view_func)def _wrapped_view(request, *args, **kwargs):ip = request.META.get('REMOTE_ADDR')cache_key = f"rate_limit_{ip}"requests = cache.get(cache_key, 0)if requests >= max_requests:return HttpResponseForbidden("Rate limit exceeded")cache.set(cache_key, requests + 1, timeout)return view_func(request, *args, **kwargs)return _wrapped_viewreturn decorator
django
Breakdown
1
def rate_limit_ip(max_requests=5, timeout=60):
Outer factory function that accepts configuration parameters for request thresholds and expiration.
2
@wraps(view_func)
Preserves original view function metadata such as docstrings and name attributes.
3
cache_key = f"rate_limit_{ip}"
Constructs a unique cache identifier derived from the client's IP address.
4
if requests >= max_requests:
Evaluates request frequency against the limit threshold before delegating to the view handler.