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(likemyapp) to namespace the keys and avoid collisions between apps. -
The
LOCATIONoption (redis://127.0.0.1:6379/1) determines the Redis instance and database number used for caching.
- Category Performance & Optimization
- Total Views 459
- Last Modified 14 April, 2026
- Tags #performance #caching #redis #backend
Previous snippet
Memcached Setup for Django
Next snippet