I use MongoDB and Motor as driver. I wrote simple Model class. After init I'm need to insert this record in DB (self._toDb
), but I can't because python doesn't allow to make __magic__ with async. I tried to use this code app.loop.call_soon(self._toDb)
, but it is never executed. Creating new event loop for this coroutine will raise exception. Help me please.
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: I tried to use ensure_future, it seems to work, but it raises exceptions
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