python异步特殊类方法__delete__ [英] python async special class methods __delete__
问题描述
海峡要点:
如何异步定义
特殊类方法,例如 __ delete __
在python中?
How can I async def
specials class methods like __delete__
in python ?
为什么我需要这样做:
实现一个在多个进程之间共享的良好的缓存系统,我想一次从数据库检索数据并将其存储在缓存中,修改缓存中的数据以及何时不再使用该数据:更新数据库。我的问题是,为了知道哪个实例是最后一个实例,我想异步使用__delete__特殊方法
In order to implement a nice caching system shared between multiple process, I want to retrieve the data from the database once and store them in a cache, modify the data in the cache and when the data is not used anymore: update the database. My problem is, in order to know which instance is the last one, I want to use the __delete__ special method asyncly
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的builint方法,但是可以使用<来调度循环外的协程调用a href = https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_future rel = nofollow noreferrer> loop.create_future
或 asyncio.ensure_future
It is impossible to async def python's builint methods but it is possible to schedule a coroutine call outside the loop using loop.create_future
or asyncio.ensure_future
class asyncdel:
def __delete__(self):
asyncio.ensure_future(free(self.__dict__.copy()))
async def free(data):
pass
这篇关于python异步特殊类方法__delete__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!