看到错误:即使在使用session.close()方法关闭会话后,未关闭的客户端会话

时间:2020-02-06 11:49:50

标签: python python-asyncio

当我运行下面的代码时,出现此错误:

TypeError: Use async with instead
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000023D639B0DA0>

该代码直接从以下位置复制:https://www.artificialworlds.net/blog/2017/06/12/making-100-million-requests-with-python-aiohttp/。注意,我尝试添加session.close()来关闭会话,但仍然收到该错误。

from aiohttp import ClientSession
import asyncio
import sys

limit = 1000

async def fetch(url, session):
    async with session.get(url) as response:
        return await response.read()

async def bound_fetch(sem, url, session):
    # Getter function with semaphore.
    async with sem:
        await fetch(url, session)

async def run(session, r):
    url = "http://localhost:8080/{}"
    tasks = []
    # create instance of Semaphore
    sem = asyncio.Semaphore(limit)
    for i in range(r):
        # pass Semaphore and session to every GET request
        task = asyncio.ensure_future(bound_fetch(sem, url.format(i), session))
        tasks.append(task)
    responses = asyncio.gather(*tasks)
    await responses

loop = asyncio.get_event_loop()
with ClientSession() as session:
    loop.run_until_complete(asyncio.ensure_future(run(session, int(sys.argv[1]))))

0 个答案:

没有答案
相关问题