gpt4 book ai didi

Python asyncio-motor 无法异步工作

转载 作者:行者123 更新时间:2023-12-01 03:06:55 24 4
gpt4 key购买 nike

我尝试了下面的示例来检查它是否为 Asyn。但它似乎不起作用。我使用了下面的代码。

import asyncio
import time
from motor.motor_asyncio import AsyncIOMotorClient


async def get_all_from_coll(col):
client = AsyncIOMotorClient("localhost", 27017)
db = client.project_matrix
cursor = db[col].find()
time.sleep(5)
for document in await cursor.to_list(length=100):
print(document)


loop = asyncio.get_event_loop()
print('001')
loop.run_until_complete(get_all_from_coll('users'))
print('002')

我按以下顺序获得输出

>>>001
>>>{'_id': ObjectId('58d9b178d011b53743d44413'), 'username': 'test1', 'password': 'test', '__v': 0}
>>>{'_id': ObjectId('58d9b229d011b53743d44414'), 'username': 'test2', 'password': 'test', '__v': 0}
>>>002

我做错了什么吗?

最佳答案

for document in await cursor.to_list(length=100):
# (wrong)

这将等待 cursor.to_list() 完成,然后再启动 for 循环。要异步运行 for 循环(一次一个文档),you should use an async for :

async for document in cursor.limit(100):
# (ok)
<小时/>

但是由于您的 print("002") 是在 loop.run_until_complete 之后执行的,所以我没有发现您的输出有任何问题命令。

关于Python asyncio-motor 无法异步工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43303795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com