Redis Caching with Django: Speed Up Your App 10x
## Install Redis
```bash
sudo apt install redis-server
pip install django-redis
```
## Django Settings
```python
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
# Use Redis for sessions too
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
```
## Cache Views
```python
from django.views.decorators.cache import cache_page
@cache_page(60 * 15) # cache for 15 minutes
def my_view(request):
...
```
## Low-Level Cache API
```python
from django.core.cache import cache
# Set
cache.set('key', expensive_result, timeout=3600)
# Get
result = cache.get('key')
if result is None:
result = expensive_db_query()
cache.set('key', result, timeout=3600)
```
## Cache Invalidation
Use versioned keys or explicit invalidation on model save:
```python
from django.db.models.signals import post_save
@receiver(post_save, sender=BlogPost)
def invalidate_blog_cache(sender, instance, **kwargs):
cache.delete(f'blog_{instance.slug}')
```