2017-07-07 53 views
5

我有一個Python discord bot,它是用discord.py構建的,意思是整個程序在事件循環中運行。在循環結束前收集python協同程序的結果

我正在處理的函數涉及製作數百個HTTP請求並將結果添加到最終列表中。大約需要兩分鐘才能完成這些操作,所以我使用aiohttp使它們異步。我的代碼的相關部分與aiohttp文檔中的快速入門示例相同,但它引發了RuntimeError:會話已關閉。該方法取自「訪問多個網址」下的https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html示例。

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 

我不知道爲什麼會出現這個錯誤,因爲我的代碼和兩個推測的功能實例非常相似。事件循環本身工作正常。它永遠運行,因爲這是一個bot應用程序。

回答

4

在你鏈接的例子中,收集的結果是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) 
+0

哇!這完全滑了我的腦海。哈哈哈,你可以說出我對異步的新感覺。感謝您的快速幫助! – user3896248