使用 asyncio 库时如何修复会话关闭错误

问题描述 投票:0回答:1

我正在尝试编写一个Python脚本来发出一堆并行的http请求。这是我到目前为止所拥有的。

async def deleteLinkRecords(req_headers):
  async with aiohttp.ClientSession(trust_env=True) as session:
   idm_url = "https://example.com"

   tasks = []
   for id in linkIdArr:
     del_url = idm_url + id
     tasks.append(make_request(session, del_url, req_headers))

  results = await asyncio.gather(*tasks)
  print(results)

async def make_request(session, url, req_headers):
    async with session.delete(url = url, headers = req_headers) as resp:
     return await resp.json()

my_headers = {
   "Authorization": "Bearer XXX"
}

linkIdArr = ["abc", "def"....]

asyncio.run(deleteLinkRecords(req_headers = my_headers))

当我运行此脚本时,出现以下错误。

Traceback (most recent call last):
  File "C:\Users\mycode.py", line 48, in <module>
    asyncio.run(deleteLinkRecords(req_headers = my_headers))
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\mycode.py", line 20, in deleteLinkRecords
    results = await asyncio.gather(*tasks)
  File "C:\Users\mycode.py", line 28, in make_requests
    async with session.delete(url = url, headers = req_headers) as resp:
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 1197, in __aenter__
    self._resp = await self._coro
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 428, in _request
    raise RuntimeError("Session is closed")
RuntimeError: Session is closed

如何解决这个问题?

python-3.x python-asyncio aiohttp
1个回答
0
投票

如果您想重用

ClientSession
,则必须将
asyncio.gather
添加到同一上下文管理器中。

async def deleteLinkRecords(req_headers):
  async with aiohttp.ClientSession(trust_env=True) as session:
   idm_url = "https://example.com"

   tasks = []
   for id in linkIdArr:
     del_url = idm_url + id
     tasks.append(make_request(session, del_url, req_headers))

   results = await asyncio.gather(*tasks)
   print(results)

async def make_request(session, url, req_headers):
    async with session.delete(url = url, headers = req_headers) as resp:
     return await resp.json()

my_headers = {
   "Authorization": "Bearer XXX"
}

linkIdArr = ["abc", "def"....]

asyncio.run(deleteLinkRecords(req_headers = my_headers))

© www.soinside.com 2019 - 2024. All rights reserved.