我正在使用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()
Run Code Online (Sandbox Code Playgroud)
这应该超时,所以我期待引发异常,并response.read()返回一个空字符串.
我怎么知道是否有超时?更好的是,优雅地处理第三方api问题的最佳方法是什么?
mou*_*uad 13
更好的是,优雅地处理第三方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)
Run Code Online (Sandbox Code Playgroud)
并且为了检查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
Run Code Online (Sandbox Code Playgroud)
如果你想要更通用的东西,你可以混合两种方式,希望这会有所帮助
urllib和httplib不会暴露超时.您必须包含套接字并在那里设置超时:
import socket
socket.settimeout(10) # or whatever timeout you want
Run Code Online (Sandbox Code Playgroud)