AsyncIOMotorClient 未连接到本地 mongodb

AsyncIOMotorClient does not connect to local mongodb

我正在尝试将我的网络 blog-like 应用程序从 Flask 移动到 Quart,这显然可以显着提高性能。

但是,我无法复制 flask_mongoengine 行为。到目前为止,我尝试了 AsyncIOMotorClient 和 quart-motor.

如果我将我的代码缩减到核心问题,问题似乎就在这里:

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]>

它没有抛出错误,但我无法从我的 collections 查询任何文档。 connect=False 是否表示某种问题?

在 pymongo 中,这段代码工作得很好:

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

我错过了什么?

终于成功了:

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())