gpt4 book ai didi

python - 获取 ServerDisconnectedError 异常,Connection.release() 会帮助解决这个问题吗?

转载 作者:行者123 更新时间:2023-12-05 08:18:39 25 4
gpt4 key购买 nike

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

问题是,当我长时间运行代码时,我开始遇到一些错误,例如 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={'{}': ''})

最佳答案

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

您可能希望将响应对象用作上下文管理器,这将有助于在您不再需要访问响应数据时更早地释放连接。您的示例代码不使用 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为了帮助您决定捕获哪些异常,这取决于您觉得需要多少细节。

关于python - 获取 ServerDisconnectedError 异常,Connection.release() 会帮助解决这个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55853195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com