我可以在django缓存中获取指定密钥的到期时间吗?

时间:2013-08-13 07:30:22

标签: django caching

必须存放在某个地方。 我可以使用set() / incr()进行更改,但我找不到阅读方式。

4 个答案:

答案 0 :(得分:4)

cache._expire_info.get('foo') 

获取unix时间戳

答案 1 :(得分:2)

获取unix时间戳:

key = cache.make_key('foo')
cache.validate_key(key)
t = cache._expire_info.get(key)

获得绝对时间:

datetime.datetime.fromtimestamp(t)

以秒为单位获取剩余时间:

(datetime.datetime.fromtimestamp(cache._expire_info.get(key)) - datetime.datetime.now()).seconds

请注意,看起来这只适用于locmem,而不是memcached,如果有人知道如何在memcached中执行此操作请注释

答案 2 :(得分:1)

正如@ austin-a所述,Django在内部存储了具有不同名称的键

示例

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

如果使用django-redis(与django-redis-cache不同),则可以在生产中的dev和redis期间使用localmemory,而redis则使用ttl方法。

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

答案 3 :(得分:1)

RedisCache具有ttl

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