Last active
December 28, 2015 23:49
-
-
Save apassant/7581639 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
###################################################### | |
## (c) 2012-2013 MDG Web limited - MIT licence | |
###################################################### | |
import cPickle | |
class RedisCache(object): | |
"""Redis cache""" | |
def __init__(self, redis, prefix='cache|', timeout=60*60): | |
"""Create Redis cache instance using a StrictRedis connection, | |
with prefix and timeout (or use default one)""" | |
assert redis | |
self._redis = redis | |
self._prefix = prefix | |
self._timeout = timeout | |
def set(self, key, value, timeout=None): | |
"""Set key-value in cache with given timeout (or use default one)""" | |
timeout = timeout or self._timeout | |
key = self._prefix + key | |
## Add key and define an expire timeout in a pipeline for atomicity | |
self._redis.pipeline().set(key, cPickle.dumps(value)).expire(key, timeout).execute() | |
def get(self, key): | |
"""Get key-value from cache""" | |
data = self._redis.get(self._prefix + key) | |
return (data and cPickle.loads(data)) or None | |
def flush(self, pattern='', step=1000): | |
"""Flush all cache (by group of step keys for efficiency), | |
or only keys matching an optional pattern""" | |
keys = self._redis.keys(self._prefix + pattern + '*') | |
[self._redis.delete(*keys[i:i+step]) for i in xrange(0, len(keys), step)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment