在Redis中存储自定义的Python对象

9

我正在尝试将一个自定义的、可序列化的Python对象存储在Redis中,但遇到了一些奇怪的行为。 set 方法似乎可以工作,但 get 方法只返回对象的 __repr__ 方法的值。例如...

import redis

# initialize the redis connection pool
rs = redis.Redis(host='localhost', port=6379)

# define a custom class
class SomeCustomObject(object):
    pass

当我尝试将 SomeCustomObject 设置为值时,它似乎有效:

<code>>>> rs.set('c', SomeCustomObject())
True
</code>

然而,当我获取值时,它只是__repr__字符串:

>>> rs.get('c')
'<__main__.SomeCustomObject object at 0x102496710>'

我应该如何存储/获取实例?在文档中,我没有找到有关此问题的信息,但我肯定不是第一个遇到这个问题的人吧?


你在哪里对对象进行序列化? - Itamar Haber
1个回答

19

使用Pickle

使用pickle模块,您可以序列化和反序列化Python对象,并将它们传递到Redis。

参考这个stackoverflow的回答 - https://dev59.com/CGUp5IYBdhLWcg3whn5z#20400288,看起来应该是这样的:

import pickle
import redis

# define a custom class
class SomeCustomObject(object):
    pass

# initialize the redis connection pool
rs = redis.Redis(host='localhost', port=6379)

# pickle and set in redis
rs.set('c', pickle.dumps(SomeCustomObject()))

# get from redis and unpickle
unpacked_object = pickle.loads(rs.get('c'))

更多阅读 - https://docs.python.org/2/library/pickle.html


啊,太好了。我之前错误地认为redis-py会处理序列化,只要我处理好了__getstate____setstate__的部分。谢谢! - TayTay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接