'Django redis cache cannot access redis cache set outside of django

I'm setting up redis as a docker service and connect to it through django-cache and python redis library.

First:

from django.http import HttpResponse
from django.core.cache import cache

def test_dj_redis(request):
    cache.set('dj_key', 'key_in_dj', 1000)
    print(cache.get('dj_key')) # works
    print(cache.get('py_key')) # Nope

    print(cache.get(':1:py_key')) # No, tried reverse engineer the prefix

    return HttpResponse("bla bla bla")

Second:

import redis
r = redis.Redis(
    host='redis',
 port=6379
)

def cache_it():
    r.set('py_key', 'key in py', 1000)
    print(r.get('py_key'))    # works
    print(r.get(':1:dj_key')) # works
    print(r.keys())           # show two keys

If I run both of them

  • first one by refresh the web page related to that django view
  • second one by python cache_it().

In first, I cannot access 'py_key', it will return None. But second, I can see cache set in django view. Django cache added a prefix to it and turn 'dj_key' into ':1:key_in_dj', but I can access it nonetheless.

Also in second, the redis_r.keys() return [b'py_key', b':1:key_in_dj'].The value of the key 'py_key' remained the same.

django cache setting

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': 'redis://redis:6379',
    },
}

Question, how do I use django.core.cache to access redis cache set outside of Django.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source