代码之家  ›  专栏  ›  技术社区  ›  rishi

带redis的python对象存储

  •  0
  • rishi  · 技术社区  · 6 年前

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

    1 回复  |  直到 6 年前
        1
  •  0
  •   0e1val    6 年前

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