Redis cache implementation

Now we are ready to build our cache on Redis using the same class interface as the earlier DiskCache class:

import json
from datetime import timedelta
from redis import StrictRedis

class RedisCache:
def __init__(self, client=None, expires=timedelta(days=30), encoding='utf-8'):
# if a client object is not passed then try
# connecting to redis at the default localhost port
self.client = StrictRedis(host='localhost', port=6379, db=0)
if client is None else client
self.expires = expires
self.encoding = encoding

def __getitem__(self, url):
"""Load value from Redis for the given URL"""
record = self.client.get(url)
if record:
return json.loads(record.decode(self.encoding))
else:
raise KeyError(url + ' does not exist')

def __setitem__(self, url, result):
"""Save value in Redis for the given URL"""
data = bytes(json.dumps(result), self.encoding)
self.client.setex(url, self.expires, data)

The __getitem__ and __setitem__ methods here should be familiar to you from the discussion on how to get and set keys in Redis in the previous section, with the exception that we are using the json module to control serialization and the setex method, which allows us to set a key and value with an expiration time. setex will accept either a datetime.timedelta or a number of seconds. This is a handy Redis feature that will automatically delete records in a specified number of seconds. This means we do not need to manually check whether a record is within our expiration guidelines, as in the DiskCache class. Let's try it out in IPython (or the interpreter of your choice) using a timedelta of 20 seconds, so we can see the cache expire:

In [1]: from chp3.rediscache import RedisCache

In [2]: from datetime import timedelta

In [3]: cache = RedisCache(expires=timedelta(seconds=20))

In [4]: cache['test'] = {'html': '...', 'code': 200}

In [5]: cache['test']
Out[5]: {'code': 200, 'html': '...'}

In [6]: import time; time.sleep(20)

In [7]: cache['test']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
...
KeyError: 'test does not exist'

The results show that our cache is working as intended and able to serialize and deserialize between JSON, dictionaries and the Redis key-value store and expire results.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset