社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Redis

带redis的python对象存储

rishi • 5 年前 • 701 次点击  

刚开始学习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 但这也出了问题。有什么简单的解决方法吗?还是必须将对象写入字符串以进行存储,然后在检索后使用字符串到对象?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30835
 
701 次点击  
文章 [ 1 ]  |  最新文章 5 年前
0e1val
Reply   •   1 楼
0e1val    5 年前

应该将dict对象而不是用户对象传递到列表中。 例子:

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()