簡體   English   中英

使用aiohttp.ClientSession的asyncio任務

[英]asyncio tasks using aiohttp.ClientSession

我正在使用python 3.7並嘗試制作可以異步進入多個域的搜尋器。 我正在為此asyncio和aiohttp使用,但是我遇到了aiohttp.ClientSession的問題。 這是我的簡化代碼:

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        print(await response.text())

async def main():
    loop = asyncio.get_event_loop()
    async with aiohttp.ClientSession(loop=loop) as session:
        cwlist = [loop.create_task(fetch(session, url)) for url in ['http://python.org', 'http://google.com']]
        asyncio.gather(*cwlist)

if __name__ == "__main__":
    asyncio.run(main())

拋出的異常是這樣的:

_GatheringFuture異常以后再也不會檢索到:<_GatheringFuture完成的異常= RuntimeError('會話已關閉')>

我在這里做錯了什么?

您忘記await asyncio.gather結果:

    async with aiohttp.ClientSession(loop=loop) as session:
        cwlist = [loop.create_task(fetch(session, url)) for url in ['http://python.org', 'http://google.com']]
        await asyncio.gather(*cwlist)

如果您曾經有一個不包含await表達式的async with那么您應該相當可疑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM