Redis caching in Django

Install redis

  1. Check that redis is running.
You should see something like (ps -ef grep redis):
  /usr/local/opt/redis/bin/redis-server 127.0.0.1:6379

1a.  Install django-redis (use pip) in a virtualenv

  1. In settings.py:

    CACHES = { “default”: { “BACKEND”: “redis_cache.cache.RedisCache”, “LOCATION”: “127.0.0.1:6379:1”, “OPTIONS”: { “CLIENT_CLASS”: “redis_cache.client.DefaultClient”, } } }

  2. And:

MIDDLEWARE_CLASSES = ( ‘django.middleware.cache.UpdateCacheMiddleware’, …… ‘django.middleware.cache.FetchFromCacheMiddleware’,

4a. In urls.py, create a “cache” entry:

url(r’cache/$’, ‘adverts.views.cache_me’),

4b.** In view.py:**

Import:

from django.views.decorators.cache import cache_page from django.core.cache import cache

from random import randint

# cache me method
@cache_page(60 * 1)
def cache_me(request):
  cache.set('a-unique-key', randint(1, 100))
  return HttpResponse(cache.get('a-unique-key'))

We are setting a key named, “a-unique-key”, with a value of a random number between 1-100. We return this as an HTTPResponse.

Point a web-browser at http://localhost:8000/cache/

You will see the number stay the same (only changing after a minute).

To check that the “a-unique-key” key is in redis, use the redis-cli command line tool:

Find out the number of keyspaces, by using the INFO command:

127.0.0.1:6379[1]> INFO

Keyspace

db0:keys=2,expires=0,avg_ttl=0 db1:keys=4,expires=4,avg_ttl=121248

SELECT Keyspace 1

127.0.0.1:6379> SELECT 1 OK

List ALL the KEYS in Keyspace 1 (use *):

127.0.0.1:6379[1]> *KEYS ** ….. 2) “:1:a-unique-key” …..

a-unique-key is in Keystore 1

Use the TYPE )to find out the type of data being stored), and HVALS to list the hash-vals for a key (which has a type of hash).

:O)

Author | Miles Davenport

Career programmer, who designs, assembles, fixes, and supports customers, software and systems.