Cache Django View with Redis
If you have views in your application that rarely change, this is a great opportunity to cache them to reduce response times. Caching your Django view will reduce unnecessary database calls and template rendering.
The first step is configuring Redis. With Docker, it's as easy as adding it to your docker-compose file and updating some settings. Make sure you add the environment variable for Redis like the following:
ENT_REDIS_LOCATION=redis://redis:6379
docker-compose.yml:
def saved_directory_path(instance, filename, root):
version: '3'
services:
web:
image: example:latest
command: python manage.py runserver 0.0.0.0:8007
volumes:
- .:/src
ports:
- "8007:8007"
depends_on:
- redis
environment:
- DJANGO_SETTINGS_MODULE=example.settings
- ENT_REDIS_LOCATION=redis://redis:6379
redis:
image: "redis:alpine"
restart: always
Next, add Redis caching to settings.
settings.py:
def saved_directory_path(instance, filename, root):
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
"LOCATION": os.getenv('ENT_REDIS_LOCATION', 'redis://127.0.0.1:6379'),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"SOCKET_CONNECT_TIMEOUT": 10,
"SOCKET_TIMEOUT": 10,
}
},
}
SESSION_EXPIRATION = 10 * 60 # x * 60 seconds
Note, instead of using environment variables you could add
redis://redis:6379
toLOCATION
here.
Finally, add redis
and django-redis
to requirements.txt
and pip install them.
Now everything is configured to cache your views and this is the easy part. To cache a view, simple add a @cache_page()
decorator.
views.py:
def saved_directory_path(instance, filename, root):
from django.views.decorators.cache import cache_page
from example import settings
from my_example import Example
CACHE_TTL = getattr(settings, 'CACHE_TTL', settings.SESSION_EXPIRATION)
class ExampleViewSet(View):
@staticmethod
@cache_page(CACHE_TTL)
def get(request):
data = Example()
data.get_get_example()
return render(request, 'example.html', {'data': example.result()})
Note,
CACHE_TTL
/SESSION_EXPIRATION
is in ms and can be defined anywhere.
After a quick docker build -t $(CONTAINER_NAME) .
and docker-compose up
, you should be good to go.
That's it folks. Your view is now cached. Enjoy those free CPU cycles.
Comments
Post a Comment