我正在编写一些代码来同时向 API 服务发出多个 POST 请求。虽然我从 aiohttp 收到以下警告,但它运行良好:
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x119340130>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x119347520>, 9.057307166)]']
connector: <aiohttp.connector.TCPConnector object at 0x119340190>
这是我用来运行它的代码(注意它们是类中的方法片段):
...
async def _request(self, ctx: dict, key: str):
async with aiohttp.ClientSession() as s:
await s.post(
self.endpoint,
json=ctx,
headers={'Authorization': 'Bearer %s' % key}
)
return
async def _gather_requests(self, key: str):
await asyncio.gather(*[self._request(ctx, key) for ctx in self._contexts])
async def _create_tasks(self):
key = await self._get_key()
await self._gather_requests(key)
def trigger(self):
asyncio.run(self._create_tasks())
我知道这个问题的常见答案是使用我已经实现的上下文管理器,我也尝试手动关闭与 s.close()
的连接,但我仍然遇到同样的问题.有什么我在这里遗漏的吗?