pythondjangoredis

Django connection to Redis


To connect Django to Redis, I have to open connection for each view:

import redis
cacheDB = redis.StrictRedis()
cacheDB.sadd("new_post", post.id)

Is there a way to create a single connection somewhere and import it into each view?


Solution

  • You can use django-redis, which allows using Redis as the backend for Django's cache framework. It supports connection pooling.

    Basic usage:

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

    Then you can use it in your view code:

    from django.core.cache import cache
    cache.set('foo', 'bar')
    

    For sadd you can use the raw Redis client:

    >>> from django_redis import get_redis_connection
    >>> con = get_redis_connection('default')
    >>> con
    <redis.client.Redis object at 0x2dc4510>