Redis Cache Setup

A snippet showing how to integrate Redis caching in Django.


# Install django-redis
pip install django-redis
      

# settings.py

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

# usage example

from django.core.cache import cache
cache.set("greeting", "hello", timeout=60)
assert cache.get("greeting") == "hello"
      
Explanation:
  • Redis stores all cached data as key-value pairs in memory for fast access.
  • You can set a KEY_PREFIX (like myapp) to namespace the keys and avoid collisions between apps.
  • The LOCATION option (redis://127.0.0.1:6379/1) determines the Redis instance and database number used for caching.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.