Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get object from redis without eval?

Tags:

python

redis

To get a key from memcache (using pylibmc), you do this:

client.set(key, {'object': 'dictionary'}, time=expire)
client.get(key)

The same in redis is this:

redis.setex(key, expire, {'object': 'dictionary'})
eval(redis.get(key) or 'None')

That last line doesn't look right to me. redis only seems to return strings. Is there a get redis to return the object in the same form that it was put in?

like image 829
priestc Avatar asked Oct 13 '12 06:10

priestc


1 Answers

Or you can even subclass Redis:

import pickle
from redis import StrictRedis


class PickledRedis(StrictRedis):
    def get(self, name):
        pickled_value = super(PickledRedis, self).get(name)
        if pickled_value is None:
            return None
        return pickle.loads(pickled_value)

    def set(self, name, value, ex=None, px=None, nx=False, xx=False):
        return super(PickledRedis, self).set(name, pickle.dumps(value), ex, px, nx, xx)

Courtesy: https://github.com/andymccurdy/redis-py/issues/186

like image 149
Sony Kadavan Avatar answered Oct 18 '22 01:10

Sony Kadavan