Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only load django_redis when Django version is lower than 4 #446

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 26 additions & 25 deletions django_prometheus/cache/backends/redis.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from django import VERSION as DJANGO_VERSION
from django_redis import cache, exceptions

from django_prometheus.cache.metrics import (
django_cache_get_fail_total,
Expand All @@ -9,30 +8,6 @@
)


class RedisCache(cache.RedisCache):
"""Inherit redis to add metrics about hit/miss/interruption ratio"""

@cache.omit_exception
def get(self, key, default=None, version=None, client=None):
try:
django_cache_get_total.labels(backend="redis").inc()
cached = self.client.get(key, default=None, version=version, client=client)
except exceptions.ConnectionInterrupted as e:
django_cache_get_fail_total.labels(backend="redis").inc()
if self._ignore_exceptions:
if self._log_ignored_exceptions:
cache.logger.error(str(e))
return default
raise
else:
if cached is not None:
django_cache_hits_total.labels(backend="redis").inc()
return cached
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

Expand All @@ -50,3 +25,29 @@ def get(self, key, default=None, version=None):
else:
django_cache_misses_total.labels(backend="native_redis").inc()
return default
else:
# Fallback for django_redis
from django_redis import cache, exceptions

class RedisCache(cache.RedisCache):
"""Inherit redis to add metrics about hit/miss/interruption ratio"""

@cache.omit_exception
def get(self, key, default=None, version=None, client=None):
try:
django_cache_get_total.labels(backend="redis").inc()
cached = self.client.get(key, default=None, version=version, client=client)
except exceptions.ConnectionInterrupted as e:
django_cache_get_fail_total.labels(backend="redis").inc()
if self._ignore_exceptions:
if self._log_ignored_exceptions:
cache.logger.error(str(e))
return default
raise
else:
if cached is not None:
django_cache_hits_total.labels(backend="redis").inc()
return cached
else:
django_cache_misses_total.labels(backend="redis").inc()
return default
Loading