Caching Django views with Redis using django-redis

(Comments)

What is Redis?

Redis is an open source, in-memory data structure store, used as a database, cache and message broker.

Redis is basically an in-memory key-value store. All the data it serves is from the main memory making it extremely efficient and is simultaneously persistent i.e., all the in-memory data is also save to storage. Redis is popularly being used as a cache server, message broker and also as database.


The analysis of pros and cons of using redis is out of scope of this blog post. We will explore how to setup caching in Django with Redis as the cache-server.

django-redis

django-redis is a redis cache backend for Django. Before we can use Redis as a cache server, we need to install and run it as a background process. Install redis with

sudo apt-get install redis-server

We can run redis server with

redis-server

Redis by default runs on port 6379. We can verify that the Redis server is running with the command redis-cli ping. The server will respond with PONG.

$ redis-cli ping
PONG

It is always best to use a process control system like supervisor which will automate the startup, restart, respawn, logging of programs.


Coming back to django-redis activate you virtual environment and install it with

pip install django-redis

To use django-redis as the cache-backend in your Django project set the cache setting as follows

CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }

assuming that the Redis server is run on the same host (hence 127.0.0.1) and on the default port 6379. That is all we need to use Redis as our cache server.


Once this is configured, we can use various methods of caching with Django's cache framework like caching the whole site, caching a single page generated by the view and caching a part of a template. Django also provides low level access to the cache which can be used to set and get cache values for key stings.


The default cache can be accessed in django with

from django.core.cache import cache

The methods to set and get a value for a key in cache is

cache.set(key, value, timeout)
cache.get(key, default=None)

The timeout value must be specified in seconds and is optional. For example, the result of the following statements is 'Hello world'.

>>> cache.set('greeting', 'Hello world', 30)
>>> cache.get('greeting')
'Hello world'

If we use the get method after 30 seconds the result will be None.

>>> cache.get('greeting') # After atleast 30 seconds
None

Django provides more methods through its cache api.

Comments

Recent Posts

Archive

2022
2021
2020
2019
2018
2017
2016
2015
2014

Tags

Authors

Feeds

RSS / Atom