获取ServerDisconnectedError异常,将连接.释放()帮助解决这个问题?

2024-10-01 05:06:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有些问题。我有一个客户端会话,它通过请求与网站通信。在

问题是,当我长时间运行代码时,我开始得到一些错误,比如ClientResponseErrorServerDisconnectedErrorError 101。所以我在看医生的时候看到了这个:

release()
Release connection back to connector.
Underlying socket is not closed, the connection may be reused later if timeout (30 seconds by default) for connection was not expired.

但我不明白。有人能简单解释一下吗?它能解决我的问题吗?在

session = aiohttp.ClientSession(cookie_jar=cookiejar)
while True:
    await session.post('https://anywhere.com', data={'{}': ''})

Tags: 代码客户端releaseaiohttp网站session错误back
1条回答
网友
1楼 · 发布于 2024-10-01 05:06:37

当连接到的服务器过早关闭连接时,将引发异常。会发生的。但是,这并不是释放到池的连接可以修复的问题,而且您发布的代码已经释放了连接,尽管是隐式的。相反,您需要处理异常,您的应用程序需要决定如何处理此错误。在

您可能希望将response对象用作上下文管理器,这将有助于在您不再需要访问响应数据时尽早释放连接。您的示例代码没有使用session.post()协程的返回值,因此当Python从内存中删除连接时(当没有对它的引用时会发生这种情况),因此已经自动为您释放连接,但是将其用作上下文管理器可以让Python通过显式方式知道您不再需要它。在

下面是一个使用(异步)上下文管理器的简单版本,它捕捉服务器断开连接时引发的异常,以及更多:

with aiohttp.ClientSession(cookie_jar=cookiejar) as session:
    while True:
        try:
            async with session.post('https://anywhere.com', data={'{}': ''}) as response:
                # do something with the response if needed

            # here, the async with context for the response ends, and the response is
            # released.
        except aiohttp.ClientConnectionError:
            # something went wrong with the exception, decide on what to do next
            print("Oops, the connection was dropped before we finished")
        except aiohttp.ClientError:
            # something went wrong in general. Not a connection error, that was handled
            # above.
            print("Oops, something else went wrong with the request")

我选择了捕捉ClientConnectionError,它是ServerDisconnectedError的派生基类,但是捕捉这个异常可以让您使用相同的异常处理程序处理更多的连接错误。请参阅exception hierarchy以帮助您决定要捕获哪些异常,这取决于您认为需要多少细节。在

相关问题 更多 >