Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Python "requests" library, how can I tell if a ConnectionError is client side or Server side?

Here is my ugly little code snippet now:

for i in range(5):
        try:
            self.startTime=time.time()
            self.rawfeed=requests.get(self.feedurl)
            continue
        except ConnectionError:
            print "Got a connection error.  Retrying", i
            time.sleep(i*i) # giving a bit longer wait each time
            pass
if i == 5: raise
self.ResponseTime=time.time()-self.startTime

Two problems here. First my except statement does not seem to recognize "ConnectionError" as an exception (SOLVED, thanks, stackers), but rather complains that it isn't a global variable. And second, and more important, I would really like to know if the error is MY side, or the SERVER's side.

Typically I want to retry on MY errors, but give up and report on a SERVER error. (By "MY" error, I mean anything other than a server error.)

like image 665
Skip Huffman Avatar asked Sep 20 '25 10:09

Skip Huffman


1 Answers

Taking a look at the requests source code, ConnectionError is only raised if it retries the maximum amount of times (MaxRetryError).

except MaxRetryError, e:
    if not self.config.get('safe_mode', False):
        raise ConnectionError(e)

It's quite impossible to say whether or not this is caused by your side or the server, as so many issues on both sides could cause this exact same error. For example, if the server's HTTP daemon is not running, your connection attempts will time out. The exact same thing will happen if you block them in your router or if your router drops the connection for some other reason.

Exception HTTPError, though, which you are not catching, is much more likely to be a server error that you can die on. ConnectionError is somewhat likely, but not at all guaranteed, to be yourself.

Your second issue is that you are not properly importing these classes. Either change your except to except requests.ConnectionError, or do from requests import ConnectionError, HTTPError.

like image 104
Fredrick Brennan Avatar answered Sep 23 '25 00:09

Fredrick Brennan