Rate Limiting Decorator

 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

  1. Decorator to limit request rates to individual views by jensbreit 5 years, 6 months ago
  2. limit view request rate decorator by anatoliy.larin 4 years, 10 months ago
  3. Error rate limiter by s29 3 years, 5 months ago
  4. superuser only decorator by jedie 4 years, 10 months ago
  5. Internet Explorer Redirect Decorator by johnboxall 5 years, 6 months ago

Comments

(Forgotten your password?)