Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests - Exception Type: ConnectionError - try: except does not work

I am using a webservice to retrieve some data but sometimes the url is not working and my site is not loading. Do you know how I can handle the following exception so there is no problem with the site in case the webservice is not working?

Django Version: 1.3.1  Exception Type: ConnectionError Exception Value:  HTTPConnectionPool(host='test.com', port=8580): Max retries exceeded with url: 

I used

try:    r = requests.get("http://test.com", timeout=0.001) except requests.exceptions.RequestException as e:    # This is the correct syntax    print e    sys.exit(1) 

but nothing happens

like image 239
user1431148 Avatar asked Jan 28 '14 13:01

user1431148


People also ask

What is ConnectionError?

Connection errors can occur for a variety of reasons. For example, a failure in any of the internal connections described in How Connection Between the Application and DBMS Server Is Established results in a connection error. How connection errors are reported depends on where the failure occurs.

How do you raise an unauthorized exception in Python?

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response. raise_for_status. That will raise an HTTPError, if the response was an http error. The exception list on the Request website isn't complete.

How does Python handle HTTP errors?

Just catch HTTPError , handle it, and if it's not Error 404, simply use raise to re-raise the exception. See the Python tutorial. can i do urllib2. urlopen("*") to handle any 404 errors and route them to my 404.


1 Answers

You should not exit your worker instance sys.exit(1) Furthermore you 're catching the wrong Error.

What you could do for for example is:

from requests.exceptions import ConnectionError try:    r = requests.get("http://example.com", timeout=0.001) except ConnectionError as e:    # This is the correct syntax    print e    r = "No response" 

In this case your program will continue, setting the value of r which usually saves the response to any default value

like image 90
ProfHase85 Avatar answered Sep 21 '22 13:09

ProfHase85