我有一个用discord.py构建的python discord bot,这意味着整个程序在一个事件循环中运行 .
函数I 'm working on involves making several hundred HTTP requests and add the results to a final list. It takes about two minutes to do these in order, so I' m使用aiohttp使它们异步 . 我的代码的相关部分与aiohttp文档中的quickstart示例相同,但它抛出了一个RuntimeError:Session已关闭 . 该方法取自https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html下'Fetch multiple URLs'的一个例子 .
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
我不知道为什么会出现这个错误,因为我的代码与两个可能的功能示例非常相似 . 事件循环本身工作正常 . 它永远运行,因为这是一个机器人应用程序 .
1 回答
在您链接的示例中,结果的收集位于
async with
块内 . 如果你在外面这样做,那么在请求发出之前就已经关闭了!在块中移动return语句应该有效: