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 ?

Karesh A
  • 1,731
  • 3
  • 22
  • 47

1 Answers1

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.

SpiXel
  • 4,338
  • 1
  • 29
  • 45
  • 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. – Karesh A Sep 16 '16 at 07:33
  • @KareshArunakirinathan You mean getting it using *cache.get("foo")* returns None ? – SpiXel Sep 16 '16 at 13:38
  • In the specific case of django-redis-client, the prefix is for versioning: `Add delta to value in the cache.` Source - https://github.com/sebleier/django-redis-cache/blob/f97ce688c73cead1db381f181f4b472f1758258d/redis_cache/backends/base.py#L332. Test - https://github.com/sebleier/django-redis-cache/blob/e76d9c102bc352786ce706c41f7739f6ceab49e0/tests/testapp/tests/base_tests.py#L392. – Avi Kaminetzky Mar 11 '20 at 16:50