[Fixed]-Can I get expiration time of specified key in django cache?

7👍

cache._expire_info.get('foo') 

to get the unix timestamp

7👍

RedisCache has ttl:

cache.ttl('foo:bar:2020-09-01')

4👍

to get the unix timestamp:

 cache_expire_time = datetime.datetime.fromtimestamp(
                    [value for key, value in cache._expire_info.items() if 'devices' in key.lower()][0]
                ) - datetime.datetime.now()

to get the remaining time in seconds:

cache_expire_time.seconds

Note that it looks like this only works for locmem, not memcached, if someone knows how to do this in memcached please comment

3👍

as @austin-a mentioned, Django stores keys with different names internally

example

import datetime

def get_key_expiration(key):
   # use make_key to generate Django's internal key storage name
   expiration_unix_timestamp = cache._expire_info.get(cache.make_key(key))
   if expiration_unix_timestamp is None:
      return 0

   expiration_date_time = datetime.datetime.fromtimestamp(expiration_unix_timestamp)
   now = datetime.datetime.now()

   # Be careful subtracting an older date from a newer date does not give zero
   if expiration_date_time < now:
       return 0

   # give me the seconds left till the key expires
   delta = expiration_date_time - now
   return delta.seconds



>> CACHE_KEY = 'x'
>> cache.set(key=CACHE_KEY, value='bla', timeout=300)
>> get_key_expiration('x')
297

Redis

If you use django-redis (different to django-redis-cache), You may use localmemory during dev and redis in production, and redis uses the ttl method instead.

from django.core.cache import cache, caches
from django_redis.cache import RedisCache

def get_key_expiration(key):
    default_cache = caches['default']

    if isinstance(default_cache, RedisCache):
        seconds_to_expiration = cache.ttl(key=key)
        if seconds_to_expiration is None:
            return 0
        return seconds_to_expiration
    else:

        # use make_key to generate Django's internal key storage name
        expiration_unix_timestamp = cache._expire_info.get(cache.make_key(key))
        if expiration_unix_timestamp is None:
            return 0
        expiration_date_time = datetime.datetime.fromtimestamp(expiration_unix_timestamp)

    now = datetime.datetime.now()

    # Be careful subtracting an older date from a newer date does not give zero
    if expiration_date_time < now:
        return 0
    # give me the seconds left till the key expires
    delta = expiration_date_time - now
    return delta.seconds

Leave a comment