Skip to content

Commit

Permalink
Support Django's official Redis cache backend. (#409)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yaser-Amiri authored Dec 12, 2023
1 parent 4f7b537 commit e967088
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
22 changes: 21 additions & 1 deletion django_prometheus/cache/backends/redis.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django import VERSION as DJANGO_VERSION
from django_redis import cache, exceptions

from django_prometheus.cache.metrics import (
django_cache_get_fail_total,
django_cache_get_total,
Expand Down Expand Up @@ -30,3 +30,23 @@ def get(self, key, default=None, version=None, client=None):
else:
django_cache_misses_total.labels(backend="redis").inc()
return default


if DJANGO_VERSION >= (4, 0):
from django.core.cache.backends.redis import RedisCache as DjangoRedisCache

class NativeRedisCache(DjangoRedisCache):

def get(self, key, default=None, version=None):
django_cache_get_total.labels(backend="native_redis").inc()
try:
result = super().get(key, default=None, version=version)
except Exception:
django_cache_get_fail_total.labels(backend="native_redis").inc()
raise
if result is not None:
django_cache_hits_total.labels(backend="native_redis").inc()
return result
else:
django_cache_misses_total.labels(backend="native_redis").inc()
return default
8 changes: 8 additions & 0 deletions django_prometheus/tests/end2end/testapp/settings.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import tempfile

from django import VERSION as DJANGO_VERSION

from testapp.helpers import get_middleware

# SECURITY WARNING: keep the secret key used in production secret!
Expand Down Expand Up @@ -131,6 +133,12 @@
},
}

if DJANGO_VERSION >= (4, 0):
CACHES["native_redis"] = {
"BACKEND": "django_prometheus.cache.backends.redis.NativeRedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
}


# Internationalization
LANGUAGE_CODE = "en-us"
Expand Down
3 changes: 3 additions & 0 deletions django_prometheus/tests/end2end/testapp/test_caches.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import pytest
from django.core.cache import caches
from django import VERSION as DJANGO_VERSION
from redis import RedisError

from django_prometheus.testutils import assert_metric_equal, get_metric

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


class TestCachesMetrics:
Expand Down

0 comments on commit e967088

Please sign in to comment.