Caching helps your Django app remember data so it can work faster next time. Different cache backends store this data in different places like memory or special servers.
0
0
Cache backends (memory, Redis, Memcached) in Django
Introduction
You want to speed up your website by saving results of slow database queries.
You need to share cached data between multiple servers using Redis or Memcached.
You want a simple cache for development using memory without extra setup.
You want to reduce load on your database by caching frequently accessed data.
You want to store session data or user info temporarily for quick access.
Syntax
Django
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', # for memory cache
'LOCATION': 'unique-snowflake', # unique name for memory cache
}
}
# For Redis
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
# For Memcached
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
'LOCATION': '127.0.0.1:11211',
}
}The BACKEND key tells Django which cache system to use.
LOCATION is where the cache stores data (memory name, Redis URL, or Memcached server address).
Examples
This sets up a simple in-memory cache for quick testing or small apps.
Django
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-memory-cache',
}
}This configures Redis as the cache backend, good for sharing cache across servers.
Django
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://localhost:6379/0',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}This uses Memcached, a fast cache server, to store cached data.
Django
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
'LOCATION': '127.0.0.1:11211',
}
}Sample Program
This example saves a greeting message in the cache for 30 seconds, then gets it back and prints it.
Django
from django.core.cache import cache # Store a value in cache for 30 seconds cache.set('greeting', 'Hello, friend!', timeout=30) # Retrieve the cached value message = cache.get('greeting', 'No greeting found') print(message)
OutputSuccess
Important Notes
Memory cache is easy to use but only works for one server and resets when the app restarts.
Redis and Memcached are better for bigger apps with many servers sharing cache.
Always set a timeout to avoid stale data staying forever in cache.
Summary
Caching stores data temporarily to make your app faster.
Django supports different cache backends like memory, Redis, and Memcached.
Choose the backend based on your app size and setup needs.