2013-03-15 17:03:56 +01:00
|
|
|
import logging
|
2012-12-05 18:01:43 +01:00
|
|
|
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
|
|
|
|
2013-08-06 21:37:34 +02:00
|
|
|
class ZulipLimiter(_RateLimitFilter):
|
2012-12-06 22:00:34 +01:00
|
|
|
pass
|
|
|
|
|
|
|
|
class EmailLimiter(_RateLimitFilter):
|
|
|
|
pass
|
2013-03-15 17:03:56 +01:00
|
|
|
|
|
|
|
class ReturnTrue(logging.Filter):
|
|
|
|
def filter(self, record):
|
|
|
|
return True
|
2013-06-10 18:57:59 +02:00
|
|
|
|
|
|
|
class RequireReallyDeployed(logging.Filter):
|
|
|
|
def filter(self, record):
|
|
|
|
from django.conf import settings
|
|
|
|
return settings.DEPLOYED and not settings.TESTING_DEPLOYED
|