|
| 1 | +from django.conf import settings |
| 2 | +from django.core import checks |
| 3 | + |
| 4 | +SUPPORTED_CACHE_BACKENDS = [ |
| 5 | + 'django.core.cache.backends.memcached.PyMemcacheCache', |
| 6 | + 'django.core.cache.backends.memcached.PyLibMCCache', |
| 7 | + 'django_redis.cache.RedisCache', |
| 8 | +] |
| 9 | + |
| 10 | +CACHE_FAKE = 'is not a real cache' |
| 11 | +CACHE_NOT_SHARED = 'is not a shared cache' |
| 12 | +CACHE_NOT_ATOMIC = 'does not support atomic increment' |
| 13 | + |
| 14 | +KNOWN_BROKEN_CACHE_BACKENDS = { |
| 15 | + 'django.core.cache.backends.dummy.DummyCache': CACHE_FAKE, |
| 16 | + 'django.core.cache.backends.locmem.LocMemCache': CACHE_NOT_SHARED, |
| 17 | + 'django.core.cache.backends.filebased.FileBasedCache': CACHE_NOT_ATOMIC, |
| 18 | + 'django.core.cache.backends.db.DatabaseCache': CACHE_NOT_ATOMIC, |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +@checks.register(checks.Tags.caches, 'django_ratelimit') |
| 23 | +def check_caches(app_configs, **kwargs): |
| 24 | + errors = [] |
| 25 | + cache_name = getattr(settings, 'RATELIMIT_USE_CACHE', 'default') |
| 26 | + caches = getattr(settings, 'CACHES', None) |
| 27 | + if caches is None: |
| 28 | + errors.append( |
| 29 | + checks.Error( |
| 30 | + 'CACHES is not defined, django_ratelimit will not work', |
| 31 | + hint='Configure a default cache using memcached or redis.', |
| 32 | + id='django_ratelimit.E001', |
| 33 | + ) |
| 34 | + ) |
| 35 | + return errors |
| 36 | + |
| 37 | + if cache_name not in caches: |
| 38 | + errors.append( |
| 39 | + checks.Error( |
| 40 | + f'RATELIMIT_USE_CACHE value "{cache_name}"" does not ' |
| 41 | + f'appear in CACHES dictionary', |
| 42 | + hint='RATELIMIT_USE_CACHE must be set to a valid cache', |
| 43 | + id='django_ratelimit.E002', |
| 44 | + ) |
| 45 | + ) |
| 46 | + return errors |
| 47 | + |
| 48 | + cache_config = caches[cache_name] |
| 49 | + backend = cache_config['BACKEND'] |
| 50 | + |
| 51 | + reason = KNOWN_BROKEN_CACHE_BACKENDS.get(backend, None) |
| 52 | + if reason is not None: |
| 53 | + errors.append( |
| 54 | + checks.Error( |
| 55 | + f'cache backend {backend} {reason}', |
| 56 | + hint='Use a supported cache backend', |
| 57 | + id='django_ratelimit.E003', |
| 58 | + ) |
| 59 | + ) |
| 60 | + |
| 61 | + if backend not in SUPPORTED_CACHE_BACKENDS: |
| 62 | + errors.append( |
| 63 | + checks.Warning( |
| 64 | + f'cache backend {backend} is not officially supported', |
| 65 | + id='django_ratelimit.W001', |
| 66 | + ) |
| 67 | + ) |
| 68 | + |
| 69 | + return errors |
0 commit comments