Skip to content

Commit e967088

Browse files
authored
Support Django's official Redis cache backend. (#409)
1 parent 4f7b537 commit e967088

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

django_prometheus/cache/backends/redis.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
from django import VERSION as DJANGO_VERSION
12
from django_redis import cache, exceptions
2-
33
from django_prometheus.cache.metrics import (
44
django_cache_get_fail_total,
55
django_cache_get_total,
@@ -30,3 +30,23 @@ def get(self, key, default=None, version=None, client=None):
3030
else:
3131
django_cache_misses_total.labels(backend="redis").inc()
3232
return default
33+
34+
35+
if DJANGO_VERSION >= (4, 0):
36+
from django.core.cache.backends.redis import RedisCache as DjangoRedisCache
37+
38+
class NativeRedisCache(DjangoRedisCache):
39+
40+
def get(self, key, default=None, version=None):
41+
django_cache_get_total.labels(backend="native_redis").inc()
42+
try:
43+
result = super().get(key, default=None, version=version)
44+
except Exception:
45+
django_cache_get_fail_total.labels(backend="native_redis").inc()
46+
raise
47+
if result is not None:
48+
django_cache_hits_total.labels(backend="native_redis").inc()
49+
return result
50+
else:
51+
django_cache_misses_total.labels(backend="native_redis").inc()
52+
return default

django_prometheus/tests/end2end/testapp/settings.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import os
22
import tempfile
33

4+
from django import VERSION as DJANGO_VERSION
5+
46
from testapp.helpers import get_middleware
57

68
# SECURITY WARNING: keep the secret key used in production secret!
@@ -131,6 +133,12 @@
131133
},
132134
}
133135

136+
if DJANGO_VERSION >= (4, 0):
137+
CACHES["native_redis"] = {
138+
"BACKEND": "django_prometheus.cache.backends.redis.NativeRedisCache",
139+
"LOCATION": "redis://127.0.0.1:6379/0",
140+
}
141+
134142

135143
# Internationalization
136144
LANGUAGE_CODE = "en-us"

django_prometheus/tests/end2end/testapp/test_caches.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import pytest
22
from django.core.cache import caches
3+
from django import VERSION as DJANGO_VERSION
34
from redis import RedisError
45

56
from django_prometheus.testutils import assert_metric_equal, get_metric
67

78
_SUPPORTED_CACHES = ["memcached.PyLibMCCache", "memcached.PyMemcacheCache", "filebased", "locmem", "redis"]
9+
if DJANGO_VERSION >= (4, 0):
10+
_SUPPORTED_CACHES.append("native_redis")
811

912

1013
class TestCachesMetrics:

0 commit comments

Comments
 (0)