如何使用 httplib (python 2.6) 处理超时?
我正在使用 httplib 通过 https 访问 api,并且需要在 api 关闭时构建异常处理。
这是一个示例连接:
connection = httplib.HTTPSConnection('non-existent-api.com', timeout=1)
connection.request('POST', '/request.api', xml, headers={'Content-Type': 'text/xml'})
response = connection.getresponse()
这应该超时,因此我期望引发异常,并且 response.read()
仅返回一个空字符串。
我如何知道是否超时?更好的是,优雅地处理第 3 方 api 关闭问题的最佳方法是什么?
I'm using httplib to access an api over https and need to build in exception handling in the event that the api is down.
Here's an example connection:
connection = httplib.HTTPSConnection('non-existent-api.com', timeout=1)
connection.request('POST', '/request.api', xml, headers={'Content-Type': 'text/xml'})
response = connection.getresponse()
This should timeout, so I was expecting an exception to be raised, and response.read()
just returns an empty string.
How can I know if there was a timeout? Even better, what's the best way to gracefully handle the problem of a 3rd-party api being down?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
API 已关闭、API 返回 http 404、500...是什么意思?
或者您的意思是 API 无法访问时?
首先,我认为您在尝试访问 Web 服务之前无法知道它是否已关闭,因此我建议您可以这样做:
并且为了检查 API 是否无法访问,我认为您会这样做最好尝试一下:
如果你想要更通用的东西,你可以混合使用两种方法,希望这会有所帮助
what's mean API is down , API return http 404 , 500 ...
or you mean when the API can't be reachable ?
first of all i don't think you can know if a web service in general is down before trying to access it so i will recommend for first one you can do like this:
and for checking if the API is not reachable i think you will be better doing a try catch:
You can mix the two ways if you want something more general ,Hope this will help
urllib 和 httplib 不公开超时。您必须包括套接字并在那里设置超时:
urllib and httplib don't expose timeout. You have to include socket and set the timeout there:
这是我发现 httplib2 可以正常工作的。发布它,因为它可能仍然对某人有帮助:
This is what I found to be working correctly with httplib2. Posting it as it might still help someone :