3

I have set the value to Redis server externally using python script.

r = redis.StrictRedis(host='localhost', port=6379, db=1)
r.set('foo', 'bar')

And tried to get the value from web request using django cache inside views.py.

from django.core.cache import cache
val = cache.get("foo")

It is returning None. But when I tries to get it form

from django_redis import get_redis_connection
con = get_redis_connection("default")
val = con.get("foo")

It is returning the correct value 'bar'. How cache and direct connections are working ?

1 Answer 1

5

Libraries usually use several internal prefixes to store keys in redis, in order not to be mistaken with user defined keys.

For example, django-redis-cache, prepends a ":1:" to every key you save into it.

So for example when you do r.set('foo', 'bar'), it sets the key to, ":1:foo". Since you don't know the prefix prepended to your key, you can't get the key using a normal get, you have to use it's own API to get.

r.set('foo', 'bar')

r.get('foo') # None
r.get(':1:foo') # bar

So in the end, it returns to the library you use, go read the code for it and see how it exactly saves the keys. redis-cli can be your valuable friend here. Basically set a key with cache.set('foo', 'bar'), and go into redis-cli and check with 'keys *' command to see what key was set for foo.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. The key is stored in redis is 'foo'. and when I set using django cache is is storing like as you said. ":1:foo" But when i get it from cache.get('') it is returning null even though the correct key is in the database.
@KareshArunakirinathan You mean getting it using cache.get("foo") returns None ?
In the specific case of django-redis-client, the prefix is for versioning: Add delta to value in the cache. Source - github.com/sebleier/django-redis-cache/blob/…. Test - github.com/sebleier/django-redis-cache/blob/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.