Uploaded image for project: 'Motor'
  1. Motor
  2. MOTOR-1334

Running async client inside different async io loops breaks the client

    • Type: Icon: New Feature New Feature
    • Resolution: Unresolved
    • Priority: Icon: Unknown 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.

       

            Assignee:
            shane.harvey@mongodb.com Shane Harvey
            Reporter:
            jaime.f@landbot.io Jaime Ferrer
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: