如何使用 httplib (python 2.6) 处理超时?

发布于 2024-09-30 11:23:15 字数 414 浏览 2 评论 0原文

我正在使用 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 技术交流群。

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

发布评论

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

评论(3

如日中天 2024-10-07 11:23:15

更好的是,优雅地处理第 3 方 API 关闭问题的最佳方法是什么?

API 已关闭、API 返回 http 404、500...是什么意思?

或者您的意思是 API 无法访问时?

首先,我认为您在尝试访问 Web 服务之前无法知道它是否已关闭,因此我建议您可以这样做:

import httplib

conn = httplib.HTTPConnection('www.google.com')  # I used here HTTP not HTTPS for simplify
conn.request('HEAD', '/')  # Just send a HTTP HEAD request 
res = conn.getresponse()

if res.status == 200:
   print "ok"
else:
   print "problem : the query returned %s because %s" % (res.status, res.reason)  

并且为了检查 API 是否无法访问,我认为您会这样做最好尝试一下:

import httplib
import socket

try:
   # I don't think you need the timeout unless you want to also calculate the response time ...
   conn = httplib.HTTPSConnection('www.google.com') 
   conn.connect()
except (httplib.HTTPException, socket.error) as ex:
   print "Error: %s" % ex

如果你想要更通用的东西,你可以混合使用两种方法,希望这会有所帮助

Even better, what's the best way to gracefully handle the problem of a 3rd-party api being down?

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:

import httplib

conn = httplib.HTTPConnection('www.google.com')  # I used here HTTP not HTTPS for simplify
conn.request('HEAD', '/')  # Just send a HTTP HEAD request 
res = conn.getresponse()

if res.status == 200:
   print "ok"
else:
   print "problem : the query returned %s because %s" % (res.status, res.reason)  

and for checking if the API is not reachable i think you will be better doing a try catch:

import httplib
import socket

try:
   # I don't think you need the timeout unless you want to also calculate the response time ...
   conn = httplib.HTTPSConnection('www.google.com') 
   conn.connect()
except (httplib.HTTPException, socket.error) as ex:
   print "Error: %s" % ex

You can mix the two ways if you want something more general ,Hope this will help

昵称有卵用 2024-10-07 11:23:15

urllib 和 httplib 不公开超时。您必须包括套接字并在那里设置超时:

import socket
socket.settimeout(10) # or whatever timeout you want

urllib and httplib don't expose timeout. You have to include socket and set the timeout there:

import socket
socket.settimeout(10) # or whatever timeout you want
扭转时空 2024-10-07 11:23:15

这是我发现 httplib2 可以正常工作的。发布它,因为它可能仍然对某人有帮助:

    import httplib2, socket

    def check_url(url):
        h = httplib2.Http(timeout=0.1) #100 ms timeout
        try:
            resp = h.request(url, 'HEAD')
        except (httplib2.HttpLib2Error, socket.error) as ex:
            print "Request timed out for ", url
            return False
        return int(resp[0]['status']) < 400

This is what I found to be working correctly with httplib2. Posting it as it might still help someone :

    import httplib2, socket

    def check_url(url):
        h = httplib2.Http(timeout=0.1) #100 ms timeout
        try:
            resp = h.request(url, 'HEAD')
        except (httplib2.HttpLib2Error, socket.error) as ex:
            print "Request timed out for ", url
            return False
        return int(resp[0]['status']) < 400
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文