1

I am writing some small python app which uses requests to get and post data to an html page.

now the problem I am having is that if I can't reach the html page the code stops with a max retries exceeded. I want to be able to do some things if I can't reach the server.

is such a thing possible?

here is sample code:

import requests

url = "http://127.0.0.1/"
req = requests.get(url)
if req.status_code == 304:
    #do something
elif req.status_code == 404:
    #do something else
# etc etc 

# code here if server can`t be reached for whatever reason

2 Answers 2

4

You want to handle the exception requests.exceptions.ConnectionError, like so:

try:
    req = requests.get(url)
except requests.exceptions.ConnectionError as e:
    # Do stuff here
Sign up to request clarification or add additional context in comments.

2 Comments

If I want to catch all exception, not just connectionerror can I remove the stuff after except? Thank you for your quick answer
Sure; but, generally speaking, I prefer to handle different classes of exception in different ways, so you might want to think carefully about how you apply that logic.
1

You may want to set a suitable timeout when catching ConnectionError:

url = "http://www.stackoverflow.com"

try:
    req = requests.get(url, timeout=2)  #2 seconds timeout
except requests.exceptions.ConnectionError as e:
    # Couldn't connect

See this answer if you want to change the number of retries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.