mongodbflaskasynchronousquartmotorengine

AsyncIOMotorClient does not connect to local mongodb


I am trying to move my web blog-like app from Flask to Quart which aparently could significantly improve the performance.

However, I am not able to replicate flask_mongoengine behaviour. So far I tried AsyncIOMotorClient and quart-motor.

If I reduce my code to the core issue, it seems that the issue is here:

from motor.motor_asyncio import AsyncIOMotorClient
client = AsyncIOMotorClient("mongodb://localhost:27017")
db= client['pets-api']
print(db)
doc = db.pet.find_one({})
print(doc)

returns:

AsyncIOMotorDatabase(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=False, driver=DriverInfo(name='Motor', version='2.3.1', platform='asyncio')), 'pets-api'))

<Future pending cb=[_chain_future.<locals>._call_check_cancel() at C:\Python39\lib\asyncio\futures.py:384]>

It doesn't throw an error, but I am not able to query any documents from my collections. Does connect=False indicate some sort of issue?

In pymongo this code works perfectly fine:

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['pets-api']
print(list(db.pet.find({})))

What am I missing?


Solution

  • This has finally worked:

    async def db_connection():
         client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://127.0.0.1:27017')
         db = client['pets-api']
         return db
    
    async def do_find_one():
         db = await db_connection()
         document = await db.user.find_one()
         pprint.pprint(document)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_find_one())