Python asyncio-motor 不能异步工作

Python asyncio-motor doesn't work Asynchronously

我试过下面的例子来检查它是否是异步的。但它似乎没有用。我使用了下面的代码。

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之后执行的,我看不出你的输出顺序有任何问题。

在上面的例子中,使用async forawait cursor.to_list()都没有关系。在任何一种情况下都会有至少一个块。如果使用 await cursor 你只阻塞一次,async for 可以有多个块。