从魔术方法调用异步方法

时间:2016-09-16 07:48:12

标签: python asynchronous python-asyncio

我使用MongoDB和Motor作为驱动程序。我写了简单的Model类。在init之后,我需要在DB(self._toDb)中插入此记录,但我不能,因为python不允许使用async生成__magic__。我尝试使用此代码app.loop.call_soon(self._toDb),但它永远不会被执行。为此协程创建新的事件循环将引发异常。请帮帮我。

class Model(abc.ABC):
    collection = db['Model']
    fields = {}

    def __init__(self, data, manual=False, doSave=True, _id=None):
        super(Model, self).__setattr__('manual', manual)
        super(Model, self).__setattr__('data', data)
        if  _id:
            super(Model, self).__setattr__('_id', _id)
        else:
            # does not work
            app.loop.call_soon(self._toDb)


    async def _toDb(self):
        super(Model, self).__setattr__('_id', await self.collection.insert(self.data) )
        print("inserted to db")

UPD: 我尝试使用ensure_future,它似乎工作,但它引发了异常

Exception in callback <Task pending coro=<Model._toDb() running at /home/oleg/python/zapdos/app/models.py:31> wait_for=<Future pending cb=[Task._wakeup()]>>
handle: <Handle <Task pending coro=<Model._toDb() running at /home/oleg/python/zapdos/app/models.py:31> wait_for=<Future pending cb=[Task._wakeup()]>>>
Traceback (most recent call last):
  File "uvloop/cbhandles.pyx", line 55, in uvloop.loop.Handle._run (uvloop/loop.c:38238)
TypeError: 'Task' object is not callable

0 个答案:

没有答案