-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Unknown
-
None
-
Affects Version/s: 3.4
-
Component/s: asyncio
-
None
-
Python Drivers
When doing queries inside asyncio loops raises execeptions about not being able to identify properly the io loop.
This is a minimun code to reproduce the issue:
import asyncio import threading import motor class Querier: def __init__(self, mongo_client): self.collection = mongo_client["contacts"] self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) async def _do_query(self): total = await self.collection.count_documents({}) print(f"Total documents: {total}") def run(self): return self.loop.run_until_complete(self._do_query()) settings = get_settings() uri = "" # replace this with a valid uri db_name = "" # replace this with a valid db_name context = motor.motor_asyncio.AsyncIOMotorClient(uri) # Uncommeting this fixes the script # context.get_io_loop = asyncio.get_event_loop client = context[db_name] query_1 = Querier(client) query_1.run() query_2 = Querier(client) query_2.run() print("finish")
That code raises the exception:
RuntimeError: Task <Task pending name='Task-2' coro=<Querier._do_query() running at /XXXXXXXX.py:16> cb=[_run_until_complete_cb() at /usr/local/lib/python3.12/asyncio/base_events.py:181]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.12/asyncio/futures.py:387]> att
However, if we overwrite the `get_io_loop` with the one coming from `asyncio` it works.
- related to
-
PYTHON-4724 Document the behavior of using an async client across multiple event loops
- Backlog