python - 使用 Redis 的 Python 对象存储
问题描述
刚开始学习Redis。来自 EhCache 背景,在 Redis 中几乎没有什么让我感到困惑。这就是我想要实现的目标:
import redis
class User:
def __init__(self, idd, name):
self.id = idd
self.name = name
cache = redis.Redis(host='localhost', port=6379, db=0)
#cache = redis.StrictRedis(host="localhost", port=6379, charset="utf-8", decode_responses=True)
user1 = User(1, 'john')
user2 = User(2, 'jack')
users_dict = {}
users_dict['1'] = user1
users_dict['2'] = user2
print(users_dict)
if not cache.exists('users'):
cache.set('users', users_dict)
users_dict_retrieved = cache.get('users')
print(users_dict_retrieved)
print(users_dict_retrieved.get('1').name)
它应该只是john
作为输出打印。这是我得到的输出:
{'1': <__main__.User object at 0x103a71710>, '2': <__main__.User object at 0x103a71780>}
b"{'1': <__main__.User object at 0x103a71710>, '2': <__main__.User object at 0x103a71780>}"
Traceback (most recent call last):
File "/Users/rishi/code/test.py", line 34, in <module>
print(users_dict_retrieved.get('1').name)
AttributeError: 'bytes' object has no attribute 'get'
但我明白了AttributeError: 'bytes' object has no attribute 'get'
。我理解这是因为当对象被检索时,它是字节形式的。我尝试使用cache = redis.StrictRedis(host="localhost", port=6379, charset="utf-8", decode_responses=True)
,但它随后也将对象表示转换为字符串。我也做了一些实验,hset
但这hget
也出错了。有什么简单的方法可以解决这个问题吗?还是我必须将对象写入字符串进行存储,然后在检索后使用字符串来对象?
解决方案
您应该将 dict 对象而不是 User 对象传递给您的列表。例子:
class User:
def __init__(self, idd, name):
self.id = idd
self.name = name
def to_dict(self):
return self.__dict__
""" rest of code """
users_dict = {}
users_dict['1'] = user1.to_dict()
users_dict['2'] = user2.to_dict()
推荐阅读
- perl - Perl - 有序多维散列(使用 Hash::Ordered)
- swift - Swift 如何在启动之前在我的应用程序的资源包中添加 pdf 文件?
- javascript - JS 和 HTML 之间未捕获的引用错误
- c++ - mciSendString 检查音乐是否正在播放
- r - 如何使用 {gtsummary} tbl_summary 包含比例的置信区间?
- typescript - 接受字符串数组并返回给定字符串作为键的对象的打字稿函数
- c# - 无法解析具有 autofac 实例的 IHttpClientFactory 并且无法从此 LifetimeScope 创建嵌套生命周期
- kubernetes - 如何找到MicroK8的IP地址
- bash - 如何使用 nmcli 按类型删除连接?
- jquery - WordPress 5.6 + 更新后 livequery 不工作