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:



version: '3'

    image: example:latest
    command: python runserver
      - .:/src
      - "8007:8007"
      - redis
      - DJANGO_SETTINGS_MODULE=example.settings
      - ENT_REDIS_LOCATION=redis://redis:6379

    image: "redis:alpine"
    restart: always

Next, add Redis caching to settings.

    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        "LOCATION": os.getenv('ENT_REDIS_LOCATION', 'redis://'),
        "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 to LOCATION 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.

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):
    def get(request):
        data = 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.

June 10, 2020, 11:55 p.m.