I have a Django application with a registered database cache:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'exchange_rate_cache',
}
}
I want the entries in my cache to expire and be deleted after a week. To delete an entry from the cache all that is needed is the following:
from django.core.cache import cache
cache.delete(key)
However I must only perform this if the entry has been stored in cache for longer than 1 week.
How can this be done? Thank you.
I think you solve the problem at the wrong level: the CACHES
settings have a setting for automatic expiration: the 'TIMEOUT'
key:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'exchange_rate_cache',
'TIMEOUT': 604800 # 7 days
}
}
This settings speicifies the number of seconds before the value "expires", or as said in the documentation [Django-doc]:
TIMEOUT
: The default timeout, in seconds, to use for the cache. This argument defaults to 300 seconds (5 minutes). You can setTIMEOUT
toNone
so that, by default, cache keys never expire. A value of0
causes keys to immediately expire (effectively “don’t cache”).
A day takes 60×60×24 seconds, and a week is 7 days, so a week has, 604800
seconds.
By adding this in the settings, you can easily change the expiration if you later change your mind.
A cache by default also holds a limited number of elements (see other settings in the documentation), and furthermore there other things can cause the cache to remove elements (for example if you use a memory cache restarting the server will normally clear the cache).
Furthermore you can - like @marin says - also ad-hoc specify an expiration for a specific key when you set(..)
it; as is specified in the documentation:
The basic interface is
set(key, value, timeout)
andget(key)
(..)
The
timeout
argument is optional and defaults to thetimeout
argument of the appropriate backend in theCACHES
setting (explained above). It’s the number of seconds the value should be stored in the cache. Passing inNone
fortimeout
will cache the value forever. A timeout of 0 won’t cache the value.