在循环结束之前从python协同程序收集结果

use*_*248 5 python asynchronous aiohttp

我有一个用discord.py构建的python discord bot,这意味着整个程序在一个事件循环中运行.

我正在处理的函数涉及发出数百个HTTP请求并将结果添加到最终列表中.按顺序执行这些操作大约需要两分钟,所以我使用aiohttp使它们异步.我的代码的相关部分与aiohttp文档中的quickstart示例相同,但它抛出了一个RuntimeError:Session已关闭.该方法取自https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html "获取多个URL"下的示例.

async def searchPostList(postUrls, searchString)
    futures = []
    async with aiohttp.ClientSession() as session:
        for url in postUrls:
            task = asyncio.ensure_future(searchPost(url,searchString,session))
            futures.append(task)

    return await asyncio.gather(*futures)


async def searchPost(url,searchString,session)):
    async with session.get(url) as response:
        page = await response.text()

    #Assorted verification and parsing
    Return data
Run Code Online (Sandbox Code Playgroud)

我不知道为什么这个错误会出现,因为我的代码与两个可能的功能示例非常相似.事件循环本身工作正常.它永远运行,因为这是一个机器人应用程序.

小智 5

在您链接的例子,结果的聚会是内部async with块.如果您在外面进行此操作,则无法保证在请求完成之前会话不会关闭!

在块中移动return语句应该有效:

async with aiohttp.ClientSession() as session:
        for url in postUrls:
            task = asyncio.ensure_future(searchPost(url,searchString,session))
            futures.append(task)

        return await asyncio.gather(*futures)
Run Code Online (Sandbox Code Playgroud)