Source

redis-dict / redis_dict.py

Full commit
try:
    import cPickle as pickle
except ImportError:
    import pickle

class RedisDict(object):

    def __init__(self, name, connection, serializer=pickle):
        self.name = name
        self.serializer = serializer
        self._redis = connection

    def __len__(self):
        return self._redis.hlen(self.name)

    def _deserialize(self, msg):
        if msg is not None and self.serializer is not None:
            msg = self.serializer.loads(msg)
        return msg

    def _serialize(self, value):
        if self.serializer is not None:
            return self.serializer.dumps(value)
        return value

    def __contains__(self, key):
        assert isinstance(key, str)
        return self._redis.hexists(self.name, key)

    def __getitem__(self, key):
        assert isinstance(key, str)
        if key in self:
            msg = self._redis.hget(self.name, key)
            return self._deserialize(msg)
        raise KeyError(key)

    def __setitem__(self, key, msg):
        assert isinstance(key, str)
        msg_ = self._serialize(msg)
        self._redis.hset(self.name, key, msg_)
        return msg

    def __delitem__(self, key):
        assert isinstance(key, str)
        self._redis.hdel(self.name, key)

    def items(self):
        return [(k, self._deserialize(v)) for k,v in self._redis.hgetall(self.name).items()]

    def execute_update(self, key, updater):
        with self._redis.pipeline() as pipe:
            pipe.watch(self.name)
            old_value = self._deserialize(pipe.hget(self.name, key))
            new_value = updater(old_value)
            pipe.multi()
            pipe.hset(self.name, key, self._serialize(new_value))
            pipe.execute()

    def get(self, key, default=None):
        return self[key] if key in self else default

    def clear(self):
        keys = self._redis.hkeys(self.name)
        if keys:
            self._redis.hdel(self.name, *keys)

    def values(self):
        return [self._deserialize(v) for v in self._redis.hvals(self.name)]

    def keys(self):
        return self._redis.hkeys(self.name)