它必须存储在某个地方。set()
我可以用/改变它incr()
,但我找不到阅读它的方法。
问问题
3651 次
4 回答
7
cache._expire_info.get('foo')
获取unix时间戳
于 2013-08-13T07:37:46.537 回答
4
获取unix时间戳:
cache_expire_time = datetime.datetime.fromtimestamp(
[value for key, value in cache._expire_info.items() if 'devices' in key.lower()][0]
) - datetime.datetime.now()
以秒为单位获取剩余时间:
cache_expire_time.seconds
请注意,这似乎仅适用于 locmem,不适用于 memcached,如果有人知道如何在 memcached 中执行此操作,请发表评论
于 2013-11-26T01:40:43.150 回答
3
RedisCache 有ttl
:
cache.ttl('foo:bar:2020-09-01')
于 2020-09-01T17:53:42.560 回答
2
正如@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
雷迪斯
如果你使用 django-redis(不同于 django-redis-cache),你可以在 dev 时使用 localmemory,在生产中使用 redis,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
于 2020-05-05T13:43:49.117 回答