Question: How to Use Redis with Django?

Answer

To use Redis with Django, you need to follow these steps:

  1. Install the necessary packages: You'll need the django-redis package for Django integration and redis package as a client library.

    pip install django-redis redis
    
  2. Configure your Django project:

    In your Django settings.py file, add the following configuration to set up django-redis as a cache backend:

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

    Replace 'redis://127.0.0.1:6379/1' with your Redis server's URL if it's not running on your local machine or using a different port.

  3. Use Redis within views or models:

    Now you can use Redis in any Django view, model, or other components to cache data or perform any desired operations. Here's an example of how to use Redis cache in a view:

    from django.core.cache import cache
    
    def my_view(request):
        # Set a value into the cache
        cache.set('my_key', 'my_value', 300)  # Cache for 300 seconds
    
        # Get a value from the cache
        my_value = cache.get('my_key')
    
        # Other cache operations are also available, such as 'add', 'get_or_set', 'incr', 'decr', etc.
    
        ...
        
    
  4. (Optional) Use Redis as a session storage backend:

    If you want to use Redis for Django session management, update your settings.py file with the following configuration:

    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
    SESSION_CACHE_ALIAS = "default"  # Use the 'default' cache alias defined earlier
    

Now you have successfully integrated Redis with Django and can use it as a cache and session storage.

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.