5

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?

4

3 に答える 3

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)  

APIに到達できないかどうかを確認するには、trycatchを実行する方がよいと思います。

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

より一般的なものが必要な場合は、2つの方法を組み合わせることができます。これが役立つことを願っています

于 2010-11-02T19:18:57.753 に答える
6

urllibとhttplibはタイムアウトを公開しません。ソケットを含め、そこでタイムアウトを設定する必要があります。

import socket
socket.settimeout(10) # or whatever timeout you want
于 2010-11-02T16:50:32.447 に答える
1

これは、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
于 2017-04-07T20:12:48.267 に答える