获取服务器断开连接错误异常,Connection.release() 会帮助解决这个问题吗?



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

问题是,当我长时间运行代码时,我开始出现一些错误,例如ClientResponseErrorServerDisconnectedErrorError 101。所以我正在阅读文档,我看到了这个:

release()
释放连接回连接器。
底层套接字 未关闭,如果超时,以后可能会重复使用连接 (默认为 30 秒)的连接未过期。

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

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

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

您可能希望将响应对象用作上下文管理器,这将有助于在您不再需要访问响应数据时更早地释放连接。您的示例代码不使用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的基类,但捕获此异常可以让您使用相同的异常处理程序处理更多连接错误情况。请参阅异常层次结构以帮助您确定要捕获的异常,这取决于您认为需要多少详细信息。

相关内容

最新更新