0
0
DjangoHow-ToBeginner · 4 min read

How to Use Redis Cache in Django: Simple Setup and Example

To use Redis cache in Django, install django-redis and configure the CACHES setting in settings.py to point to your Redis server. Then use Django's cache API like cache.set() and cache.get() to store and retrieve cached data.
📐

Syntax

Configure Redis cache in Django by setting the CACHES dictionary in settings.py. Use django_redis.cache.RedisCache as the backend and provide the Redis server URL. Then use Django's cache object to interact with the cache.

  • BACKEND: Specifies Redis cache backend.
  • LOCATION: Redis server URL (e.g., redis://127.0.0.1:6379/1).
  • OPTIONS: Additional settings like client class.
python
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient"
        }
    }
}
💻

Example

This example shows how to set a value in Redis cache and then retrieve it using Django's cache API.

python
from django.core.cache import cache

# Set a cache key 'greeting' with value 'Hello, Redis!' for 60 seconds
cache.set('greeting', 'Hello, Redis!', timeout=60)

# Retrieve the cached value
value = cache.get('greeting')
print(value)  # Output: Hello, Redis!
Output
Hello, Redis!
⚠️

Common Pitfalls

  • Not installing django-redis package before configuring Redis cache.
  • Incorrect Redis server URL or port causing connection errors.
  • Forgetting to run a Redis server locally or on the specified host.
  • Using cache.get() without checking for None if the key is missing.
  • Setting very short or very long cache timeouts without reason.

Always test your Redis connection and handle cache misses gracefully.

python
from django.core.cache import cache

# Wrong: Assuming key always exists
value = cache.get('missing_key')
print(value.upper())  # This will raise AttributeError if value is None

# Right: Check before using
value = cache.get('missing_key')
if value is not None:
    print(value.upper())
else:
    print('Cache miss')
Output
Cache miss
📊

Quick Reference

Remember these key points when using Redis cache in Django:

  • Install django-redis with pip install django-redis.
  • Configure CACHES in settings.py with Redis backend and location.
  • Use cache.set(key, value, timeout) and cache.get(key) to store and retrieve data.
  • Ensure Redis server is running and accessible.
  • Handle cache misses by checking if cache.get() returns None.

Key Takeaways

Install and configure django-redis to connect Django cache to Redis.
Use Django's cache API to set and get cached data easily.
Always verify Redis server is running and reachable.
Handle cache misses by checking for None before using cached values.
Set appropriate cache timeouts to balance performance and freshness.