2012-12-05 18:01:43 +01:00
|
|
|
import traceback
|
|
|
|
from hashlib import sha256
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
|
|
|
# Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010)
|
|
|
|
|
2012-12-06 22:00:34 +01:00
|
|
|
class _RateLimitFilter(object):
|
2012-12-11 02:02:58 +01:00
|
|
|
last_error = datetime.min
|
2012-12-05 18:01:43 +01:00
|
|
|
|
|
|
|
def filter(self, record):
|
|
|
|
from django.conf import settings
|
|
|
|
from django.core.cache import cache
|
|
|
|
|
|
|
|
# Track duplicate errors
|
|
|
|
duplicate = False
|
2012-12-06 22:00:34 +01:00
|
|
|
rate = getattr(settings, '%s_LIMIT' % self.__class__.__name__.upper(),
|
|
|
|
600) # seconds
|
2012-12-05 18:01:43 +01:00
|
|
|
if rate > 0:
|
|
|
|
# Test if the cache works
|
|
|
|
try:
|
|
|
|
cache.set('RLF_TEST_KEY', 1, 1)
|
|
|
|
use_cache = cache.get('RLF_TEST_KEY') == 1
|
|
|
|
except:
|
|
|
|
use_cache = False
|
|
|
|
|
|
|
|
if use_cache:
|
2012-12-06 22:00:34 +01:00
|
|
|
key = self.__class__.__name__.upper()
|
|
|
|
duplicate = cache.get(key) == 1
|
|
|
|
cache.set(key, 1, rate)
|
2012-12-05 18:01:43 +01:00
|
|
|
else:
|
|
|
|
min_date = datetime.now() - timedelta(seconds=rate)
|
|
|
|
duplicate = (self.last_error >= min_date)
|
|
|
|
if not duplicate:
|
|
|
|
self.last_error = datetime.now()
|
|
|
|
|
|
|
|
return not duplicate
|
2012-12-06 22:00:34 +01:00
|
|
|
|
|
|
|
class HumbugLimiter(_RateLimitFilter):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class EmailLimiter(_RateLimitFilter):
|
|
|
|
pass
|