Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I expire entries to Django database cache?

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.

like image 404
Tom Finet Avatar asked Jan 02 '23 23:01

Tom Finet


2 Answers

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 set TIMEOUT to None so that, by default, cache keys never expire. A value of 0 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) and get(key)

(..)

The timeout argument is optional and defaults to the timeout argument of the appropriate backend in the CACHES setting (explained above). It’s the number of seconds the value should be stored in the cache. Passing in None for timeout will cache the value forever. A timeout of 0 won’t cache the value.

like image 166
Willem Van Onsem Avatar answered Jan 04 '23 12:01

Willem Van Onsem


redis_time_cache = 180 # seconds
cache.set(key, data, redis_time_cache)
  1. key = 'my_key'
  2. data = JSON or STRING
  3. redis_time_cache = TIMEOUT
like image 44
Marin Avatar answered Jan 04 '23 13:01

Marin