gpt4 book ai didi

python - 在 Redis 中存储自定义 Python 对象

转载 作者:IT王子 更新时间:2023-10-29 05:58:55 28 4
gpt4 key购买 nike

我试图在 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 设置为一个值时,它似乎有效:

>>> rs.set('c', SomeCustomObject())
True

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

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

如何存储/取回实例?我运气不太好,在 the documentation 中找到了这方面的任何信息。 ,但我肯定不是第一个遇到这种情况的人吧?

最佳答案

使用 Pickle

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

从这个答案 - 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

关于python - 在 Redis 中存储自定义 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283469/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com