【问题标题】:AsyncIOMotorClient does not connect to local mongodbAsyncIOMotorClient 未连接到本地 mongodb
【发布时间】:2021-06-08 22:04:46
【问题描述】:

我正在尝试将我的类似网络博客的应用从 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)

返回:

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

它不会引发错误,但我无法从我的集合中查询任何文档。 connect=False 是否表示某种问题?

在 pymongo 中,这段代码运行良好:

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

我错过了什么?

【问题讨论】:

    标签: mongodb flask asynchronous quart motorengine


    【解决方案1】:

    这终于奏效了:

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

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2017-10-03
      • 2019-11-15
      • 2022-05-05
      • 1970-01-01
      相关资源
      最近更新 更多