djangodjango-rest-frameworkredisdjango-cachedjango-redis

Django Redis cache get TTL (expire time)


Is it possible to get key's expire time in Django using Redis cache?
Something like:

from django.core.cache import cache  

cache.get_expire('mykey')  # 300 (seconds)

I tried:

cache.ttl('my_key')  

getting an error

AttributeError: 'RedisCache' object has no attribute 'ttl'

Solution

  • There is no official API to get TTL from RedisCache backend in Django (as of Django 4.2); but we can customize the backend like -

    # somefile.py
    
    from functools import cached_property
    
    from django.core.cache.backends.redis import (
        RedisCache as _RedisCache,
        RedisCacheClient as _RedisCacheClient,
    )
    
    
    class RedisCacheClient(_RedisCacheClient):
        def ttl(self, key):
            client = self.get_client(key)
            return client.ttl(key)
    
    
    class RedisCache(_RedisCache):
        @cached_property
        def _cache(self):
            return RedisCacheClient(self._servers, **self._options)
    
        def ttl(self, key, version=None):
            key = self.make_and_validate_key(key, version=version)
            return self._cache.ttl(key)
    

    and then update your settings.py

    # settings.py
    
    CACHES = {
        "default": {
            "BACKEND": "path.to.new.custom.backend.RedisCache",
            # other parameters and options
        },
    }
    

    Results

    In [1]: from django.core.cache import cache
    
    In [2]: cache.get("test")
    
    In [3]: cache.set("test", "Foo", 30)
    
    In [4]: cache.get("test")
    Out[4]: 'Foo'
    
    In [5]: cache.ttl("test")
    Out[5]: 21
    
    In [6]: cache.ttl("test")
    Out[6]: 19
    
    In [7]: cache.ttl("any-key")
    Out[7]: -2