Python httplib.HTTPSConnection 超时——连接与响应

发布于 2024-11-28 07:21:44 字数 507 浏览 0 评论 0原文

使用httplib 创建HTTPSConnection 时,很容易设置超时:

connection = httplib.HTTPSConnection('some.server.com', timeout=10)
connection.request('POST', '/api', xml, headers={'Content-Type': 'text/xml'})
response = connection.getresponse().read()

此操作有多个部分,例如接受连接和接收响应。

超时是否适用于整个操作?如果远程主机接受连接但从未发回响应,是否仍然会超时?我想确保设置超时可确保操作最多阻塞 10 秒。

一些上下文:

我正在连接到外部 API 并希望阻止该操作。只是不要超过10秒,如果阻塞超过10秒,则停止阻塞并引发异常。当外部 API 无法访问时,我正确处理了这种情况,但不确定它何时接受我的连接但无法响应。

When creating an HTTPSConnection with httplib, easy enough to set a timeout:

connection = httplib.HTTPSConnection('some.server.com', timeout=10)
connection.request('POST', '/api', xml, headers={'Content-Type': 'text/xml'})
response = connection.getresponse().read()

There are various parts to this operation, e.g. the connection being accepted and a response being received.

Does the timeout apply to the entire operation? Will it still timeout if the remote host accepts the connection but never sends back a response? I want to be sure that setting the timeout ensure that the operation blocks for a maximum of 10 seconds.

Some context:

I am connecting to an external API and want the operation to block. Just not for more than 10 seconds, and if it is blocking for more than 10 seconds, stop blocking and raise an exception. I'm correctly handling the case when an external API is unreachable, but unsure about when it accepts my connection but fails to respond.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜深人未静 2024-12-05 07:21:44

标准库实现似乎不支持套接字读取操作的超时。为此,您必须使 HTTPSConnection (技术上是 HTTPResponse._safe_read 方法)成为非阻塞的。

这里有一个类似的问题,可能也有帮助:

Does python's httplib.HTTPConnection block?

如果您的情况可能的话,我会在整个应用程序中使用 gevent ,它完全支持非阻塞 I/O,您可以实现任何您想要的超时方案,甚至可以同时实现多个连接。

It seems the standard library implementation does not support a timeout on the socket read operations. You would have to make the HTTPSConnection (technically the HTTPResponse._safe_read method) non-blocking for this.

There is a similar question here, which might also help:

Does python's httplib.HTTPConnection block?

I would use gevent for the whole application if that's possible in your case, that supports fully non-blocking I/O and you can implement any timeout scheme you want, even for multiple connections at once.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文