Skip to content

Instantly share code, notes, and snippets.

@jcockhren
Forked from levigross/djangoratelimit.py
Created May 15, 2014 06:25
Show Gist options
  • Save jcockhren/3e30d0446be003bec865 to your computer and use it in GitHub Desktop.
Save jcockhren/3e30d0446be003bec865 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment