我正在尝试实现 redis 实际保存属性的类,但该类的用户不知道这一点(即跨多个客户端的对象持久性)。我知道有一些库为 python 包装了 redis,但没有一个库以这种简单的方式做到这一点(但如果我错了,请纠正我!)
__getattribute__
我已经成功地实现了属性的自动 redis 存储,但如果没有无限递归将其炸毁,我似乎无法使用它进行检索。我想我在使用object.__getattribute__
等方面很小心,但显然我必须遗漏一些东西:
class redisStored(object):
global redis
# A class method to implement object retrieval from redis
# Call <Classname>.load(<id>) to create a new instance which exists in redis
@classmethod
def load(cls,id):
# Create the object
obj = cls.__new__(cls)
# Set id without calling obj's __setattr__
object.__setattr__(obj,'id',int(id))
# Return the object we created
return obj
def __str__(self):
# Return "<ClassName>:<id>" to differentiate ids in redis
# You can use this to say redis.hgetall(g) where g is the instance
return "%s:%s" % (self.__class__.__name__, str(object.__getattribute__(self,'id')))
# self.id here ^ would cause infinite recursion
# This works fine
def __setattr__(self,name,value):
redis.hset(self,name,value)
return object.__setattr__(self,name,value)
# This blows up with infinite recursion, WHY??
def __getattribute__(self,name):
_val = redis.hget(self,name)
if not _val:
return object.__getattribute__(self,name)
else:
return _val
如果我追踪它,它会在里面爆炸,_val = redis.hget(self,name)
但我不知道为什么。谢谢你的帮助!