Mercurial > public > sg101
comparison gpp/antispam/decorators.py @ 505:a5d11471d031
Refactor the logic in the rate limiter decorator. Check to see if the request was ajax, as the ajax view always returns 200. Have to decode the JSON response to see if an error occurred or not.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 03 Dec 2011 19:13:38 +0000 |
parents | 32cec6cd8808 |
children |
comparison
equal
deleted
inserted
replaced
504:b5bd3509e6e6 | 505:a5d11471d031 |
---|---|
4 """ | 4 """ |
5 from datetime import timedelta | 5 from datetime import timedelta |
6 from functools import wraps | 6 from functools import wraps |
7 | 7 |
8 from django.shortcuts import render | 8 from django.shortcuts import render |
9 from django.utils import simplejson | |
9 | 10 |
10 from antispam.rate_limit import RateLimiter, RateLimiterUnavailable | 11 from antispam.rate_limit import RateLimiter, RateLimiterUnavailable |
11 | 12 |
12 | 13 |
13 def rate_limit(count=10, interval=timedelta(minutes=1), | 14 def rate_limit(count=10, interval=timedelta(minutes=1), |
29 return fn(request, *args, **kwargs) | 30 return fn(request, *args, **kwargs) |
30 | 31 |
31 response = fn(request, *args, **kwargs) | 32 response = fn(request, *args, **kwargs) |
32 | 33 |
33 if request.method == 'POST': | 34 if request.method == 'POST': |
34 success = (response and response.has_header('location') and | 35 |
35 response.status_code == 302) | 36 # Figure out if the view succeeded; if it is a non-ajax view, |
36 try: | 37 # then success means a redirect is about to occur. If it is |
37 if not success and rate_limiter.incr(): | 38 # an ajax view, we have to decode the json response. |
39 success = False | |
40 if not request.is_ajax(): | |
41 success = (response and response.has_header('location') and | |
42 response.status_code == 302) | |
43 elif response: | |
44 json_resp = simplejson.loads(response.content) | |
45 success = json_resp['success'] | |
46 | |
47 if not success: | |
48 try: | |
49 blocked = rate_limiter.incr() | |
50 except RateLimiterUnavailable: | |
51 blocked = False | |
52 | |
53 if blocked: | |
38 return render(request, 'antispam/blocked.html', status=403) | 54 return render(request, 'antispam/blocked.html', status=403) |
39 | |
40 except RateLimiterUnavailable: | |
41 pass | |
42 | 55 |
43 return response | 56 return response |
44 | 57 |
45 return wrapped | 58 return wrapped |
46 return decorator | 59 return decorator |