- Author:
- levigross
- Posted:
- November 28, 2010
- Language:
- Python
- Version:
- 1.2
- Score:
- 3 (after 3 ratings)
This is a small and useful decorator that you can use to protect yourself from bad users or bots hitting your site.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | from django.core.cache import cache
from django.http import HttpResponseForbidden
from functools import wraps
from django.utils.decorators import available_attrs
def ratelimit(limit=10,length=86400):
""" The length is in seconds and defaults to a day"""
def decorator(func):
def inner(request, *args, **kwargs):
ip_hash = str(hash(request.META['REMOTE_ADDR']))
result = cache.get(ip_hash)
if result:
result = int(result)
if result == limit:
return HttpResponseForbidden("Ooops too many requests today!")
else:
result +=1
cache.set(ip_hash,result,length)
return func(request,*args,**kwargs)
cache.add(ip_hash,1,length)
return func(request, *args, **kwargs)
return wraps(func, assigned=available_attrs(func))(inner)
return decorator
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.