Login

Use memcached to throttle POSTs

Author:
coleifer
Posted:
May 8, 2010
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

Problem: you want to limit posts to a view

This can be accomplished with a view decorator that stores hits by IP in memcached, incrementing the cached value and returning 403's when the cached value exceeds a certain threshold for a given IP.

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

tttallis (on August 23, 2011):

I think the first line should be:

from django.core.cache import cache

#

Please login first before commenting.