Python httplib.HTTPSConnection 超时——连接与响应
使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标准库实现似乎不支持套接字读取操作的超时。为此,您必须使
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 theHTTPResponse._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.