djangoredisdjango-redis

Why django redis cache cannot get the data in redis


My cache settings:

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
        'OPTIONS': {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },
    }
}

the host is 127.0.0.1, the port is 6379 and database is 1.

I want to add the data by using redis_connection like this:

from django_redis import get_redis_connection

redis_conn = get_redis_connection('default')
redis_conn.set('somekey', 'somevalue')

So the redis database has the data now, I can get it by:

redis_conn.get('somekey')

but I couldn't get it by django.core.cache.cache, although data exists in the database:

from django.core.cache import cache
cache.get('somekey')  #return None

If I must use conn to set data and use cache to get data, what should I do?


Solution

  • The Django cache adds a prefix to cache keys. By default, this depends on KEY_PREFIX and VERSION in your CACHES settings. You can also customise the behaviour by using a custom KEY_FUNCTION.

    You can use the make_key method to find out the full cache key:

    >>> from django.core.cache import cache
    >>> cache.make_key('somekey')
    ':1:somekey'
    

    You can use this full key when you call redis_conn.set().

    As you pointed out in the comments, there is a second difficulty. Django-redis serializes the cache values. By default it uses Python pickle but there is also a JSON serializer available or you can choose your own.

    When you write to the cache using redis_conn.set(), you will have to serialize the data in the same way so that django-redis can read it.