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
Charles
  • 50,943
  • 13
  • 104
  • 142

2 Answers2

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
TML
  • 12,813
  • 3
  • 38
  • 45
  • If I want to catch all exception, not just connectionerror can I remove the stuff after except? Thank you for your quick answer –  May 15 '14 at 17:13
  • 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. – TML May 15 '14 at 17:15
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.

Community
  • 1
  • 1
lpszBar
  • 11
  • 3