Use memcached to throttle POSTs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.utils.cache import cache
from django.http import HttpResponseForbidden

def throttle_post(func, duration=15):
    def inner(request, *args, **kwargs):
        if request.method == 'POST':
            remote_addr = request.META.get('HTTP_X_FORWARDED_FOR') or \
                          request.META.get('REMOTE_ADDR')
            key = '%s.%s' % (remote_addr, request.get_full_path())
            if cache.get(key):
                return HttpResponseForbidden('Try slowing down a little.')
            else:
                cache.set(key, 1, duration)
        return func(request, *args, **kwargs)
    return inner

More like this

  1. Decorator to limit request rates to individual views by jensbreit 4 years, 8 months ago
  2. Property Attributes in Memcache by ori 1 year, 6 months ago
  3. Scalable and invalidateble cache_page decorator by marinho 4 years ago
  4. Tags & filters for rendering search results by exogen 5 years, 2 months ago
  5. Decorator that limits request methods by schinckel 3 years, 10 months ago

Comments

tttallis (on August 23, 2011):

I think the first line should be:

from django.core.cache import cache

#

(Forgotten your password?)