Login

Rate Limiting Decorator

Author:
levigross
Posted:
November 28, 2010
Language:
Python
Version:
1.2
Tags:
security cache-based-rate-limiting protection rate limiting
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

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

Comments

Please login first before commenting.