首页 > 解决方案 > 使用 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也出错了。有什么简单的方法可以解决这个问题吗?还是我必须将对象写入字符串进行存储,然后在检索后使用字符串来对象?

标签: pythonredis

解决方案


您应该将 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()

推荐阅读