在没有eval的情况下从redis获取对象? [英] get object from redis without eval?

查看:51
本文介绍了在没有eval的情况下从redis获取对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要从 memcache 获取密钥(使用 pylibmc),您可以这样做:

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

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

在redis中也是这样:

The same in redis is this:

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

最后一行在我看来不太合适.redis 似乎只返回字符串.是否有 get redis 以与放入的相同形式返回对象?

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?

推荐答案

不同的是,虽然 memcached 和 redis 都只支持字符串值,但 pylibmc 使用 pickleredis-py 只是将它们转换为字符串.

The difference is that while both memcached and redis only support string values, pylibmc serializes the values you send it using pickle, redis-py just converts them to string.

如果你想用redis做同样的事情,你可以有自己的函数来为你做酸洗.

If you want to do the same with redis, you can have your own functions to do the pickling for you.

def set_value(redis, key, value):
    redis.set(key, pickle.dumps(value))

def get_value(redis, key):
    pickled_value = redis.get(key)
    if pickled_value is None:
        return None
    return pickle.loads(pickled_value)

这篇关于在没有eval的情况下从redis获取对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆