It must be stored somewhere.
I can change it with set()
/incr()
, but I couldn't find the way to read it.
To set output-cache expirations for a page programmatically In the page's code, set the expiration policy for the page on the Cache property of the Response object. If you set expirations for a page programmatically, you must set the Cache-Control header for the cached page as well.
TIMEOUT : The default timeout, in seconds, to use for the cache. This argument defaults to 300 seconds (5 minutes). You can set TIMEOUT to None so that, by default, cache keys never expire.
To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project.
cache._expire_info.get('foo')
to get the unix timestamp
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With