如何解决Python aiohttp未关闭连接器的报错问题?
解决aiohttp未关闭连接器的问题
问题出在你设置的connector_owner=False参数上。这个参数会让ClientSession放弃对连接器的所有权——当async with块结束、session自动关闭时,连接器不会被一同关闭,残留的连接就会触发这个报错。你手动加await session.close()没用,因为session本身已经被正确关闭了,问题根源在连接器没被处理。
方案一:移除connector_owner=False(推荐)
让ClientSession默认拥有连接器所有权,这样关闭session时会自动关闭所有连接:
def async_aiohttp_get_all(self, urls): """ Performs asynchronous get requests """ async def get_all(urls): # 移除connector_owner=False,使用默认的连接器所有权设置 async with aiohttp.ClientSession() as session: async def fetch(url): async with session.get(url) as response: rtn = {"url": response.url, "content": await response.text()} return rtn rslts = await asyncio.gather(*[ fetch(url) for url in urls ]) return rslts # Call get_all as a sync function to be used in a sync context return sync.async_to_sync(get_all)(urls)
方案二:显式管理连接器生命周期(仅当必须保留connector_owner=False时使用)
如果你的场景需要复用连接器,得手动创建并关闭它:
def async_aiohttp_get_all(self, urls): """ Performs asynchronous get requests """ async def get_all(urls): # 显式创建连接器 connector = aiohttp.TCPConnector() try: async with aiohttp.ClientSession(connector=connector, connector_owner=False) as session: async def fetch(url): async with session.get(url) as response: rtn = {"url": response.url, "content": await response.text()} return rtn rslts = await asyncio.gather(*[ fetch(url) for url in urls ]) return rslts finally: # 手动关闭连接器,确保所有连接被清理 await connector.close() # Call get_all as a sync function to be used in a sync context return sync.async_to_sync(get_all)(urls)
绝大多数场景下,方案一就能解决问题,因为默认配置已经能让ClientSession自动处理连接器的生命周期。
内容的提问来源于stack exchange,提问作者fattyres.co.uk
相关产品推荐
相关产品推荐

