在Redis中存储自定义Python对象

2024-10-04 11:34:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Redis中存储一个自定义的、可序列化的python对象,但是遇到了一些奇怪的行为。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设置为一个值时,它似乎可以工作:

^{pr2}$

但是,当我get返回值时,它只是__repr__字符串:

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

如何存储/获取实例?我在the documentation中没有找到任何关于这方面的信息,但我肯定不是第一个遇到这种情况的人?在


Tags: the对象方法importredisget序列化object
1条回答
网友
1楼 · 发布于 2024-10-04 11:34:05

使用Pickle

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

从这个so答案-https://stackoverflow.com/a/20400288/4403600可以看出:

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

相关问题 更多 >