Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend cache ttl (time-to-live) in django-redis?

I'm using django 1.5.4 and django-redis 3.7.1

I'd like to extend cache's ttl(time-to-live) when I retrieved it.

Here is sample code

from django.core.cache import cache

foo = cache.get("foo)

if not foo:
    cache.set("foo", 1, timeout=100)
else:
    // Extend Cache's Time-To-Live something like it
    cache.ttl("foo") = 200

I tried to search this option at django-redis-docs, but I couldn't find it.

However, I noticed that designate time-to-live value for existing cache is available at redis native command like "Expire foo 100"

I know that using cache.set once more make same effect, but I'd like to use more simple method with time-to-live attribute.

like image 484
Chemical Programmer Avatar asked Aug 23 '14 14:08

Chemical Programmer


People also ask

What are the caching strategies in Django?

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.

What is the default value of cull frequency of cache backend?

CULL_FREQUENCY : The fraction of entries that are culled when MAX_ENTRIES is reached. The actual ratio is 1 / CULL_FREQUENCY , so set CULL_FREQUENCY to 2 to cull half the entries when MAX_ENTRIES is reached. This argument should be an integer and defaults to 3 .

Is Django cache thread-safe?

Django relies on the cache backend to be thread-safe, and a single instance of a memcache. Client is not thread-safe. The issue is with Django only creating a single instance that is shared between all threads (django. core.


1 Answers

To extend a ttl(time-to-live) of the django-redis cache record use expire(key, timeout)

Django-Redis: Expire & Persist

from django.core.cache import cache

cache.set("foo", 1, timeout=100)
cache.ttl("foo")
>>> 100

You cannot extend ttl(time-to-live) if the key already expired

if cache.ttl("foo") > 0:
    cache.expire("foo", timeout=500)

cache.ttl("foo")
>>> 500
like image 142
Egor Bolotevich Avatar answered Oct 13 '22 19:10

Egor Bolotevich