海峡到点:
我怎么能够async def
特殊类方法,例如__delete__
在Python中?
为什么我需要这个:
为了实现在多个进程之间共享的良好缓存系统,我想从数据库中检索一次数据并将它们存储在缓存中,修改缓存中的数据,当不再使用数据时:更新数据库。我的问题是,为了知道哪个实例是最后一个,我想异步使用 __delete__ 特殊方法
def asyncinit(cls):
"""Credits: http://stackoverflow.com/a/33140788/4241798"""
__new__ = cls.__new__
async def init(obj, *arg, **kwarg):
await obj.__init__(*arg, **kwarg)
return obj
def new(cls, *arg, **kwarg):
obj = __new__(cls, *arg, **kwarg)
coro = init(obj, *arg, **kwarg)
return coro
cls.__new__ = new
return cls
@asyncinit
class AsyncUser:
async def __init__(self, id: int):
self.id = id
with await cachepool as cache:
cache.hincr(f"users:{id}", "refcnt")
async def __delete__(self):
"""Won't work"""
with await cachepool as cache:
refcnt = await cache.hincrby(f"users:{self.id}", "refcnt", -1)
if refcnt == 0:
# update database
# rest of the class...
不可能异步 def python 内置方法,但可以使用以下命令在循环外部安排协程调用loop.create_future or asyncio.ensure_future
class asyncdel:
def __delete__(self):
asyncio.ensure_future(free(self.__dict__.copy()))
async def free(data):
pass
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)