使用TaskGroup结合Motor Aggregate时遭遇StopAsyncIteration错误
使用TaskGroups迭代Motor聚合结果时出现StopAsyncIteration错误
在使用asyncio.TaskGroups并行迭代Motor的聚合查询结果时,会抛出StopAsyncIteration错误,但串行执行或先串行后并行的场景下无此问题。
复现代码
import asyncio from motor.motor_asyncio import AsyncIOMotorClient def create_aggregate(): client = AsyncIOMotorClient("mongodb://localhost:27017") collection = client["test"]["test"] return collection.aggregate([]) async def get_next(agg): item = await agg.next() print(item) async def run_1_success(): agg = create_aggregate() await get_next(agg) async def run_2_success(): agg = create_aggregate() await get_next(agg) async with asyncio.TaskGroup() as tg: tg.create_task(get_next(agg)) tg.create_task(get_next(agg)) async def run_3_error(): agg = create_aggregate() async with asyncio.TaskGroup() as tg: tg.create_task(get_next(agg)) tg.create_task(get_next(agg))
运行情况
- 执行
asyncio.run(run_1_success())或asyncio.run(run_2_success()),迭代正常完成 - 执行
asyncio.run(run_3_error()),抛出StopAsyncIteration错误
环境信息
- Python 3.12.2 (tags/v3.12.2:6abddd9, Feb 6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)]
- Motor 3.4.0
- PyMongo 4.6.2
- Windows 10 64位
内容的提问来源于stack exchange,提问作者minimino
相关产品推荐
相关产品推荐

