Chemical Programmer
Chemical Programmer

Reputation: 4520

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.

Upvotes: 8

Views: 10619

Answers (2)

Egor  Bolotevich
Egor Bolotevich

Reputation: 118

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

Upvotes: 8

Chemical Programmer
Chemical Programmer

Reputation: 4520

I solved this problem.

(1) Using 'Raw Client Access' and (2) Extend TTL value without overwriting

Please refer following code.

from redis_cache import get_redis_connection

con = get_redis_connection('default')

con.expire(":{DB NUMBER at settings.py}:" + "foo", 100)

Upvotes: 1

Related Questions