r = requests.get('http://example.com')
print str(r.status_code)
I want to check if my server is both down or a internal 500 error.
How can I check both using requests?
Requests throws different types of exceptions depending on what's causing your request to fail.
import requests.exceptions
try:
    r = requests.get('http://example.com')
    r.raise_for_status()  # Raises a HTTPError if the status is 4xx, 5xxx
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
    print "Down"
except requests.exceptions.HTTPError:
    print "4xx, 5xx"
else:
    print "All good!"  # Proceed to do stuff with `r` 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With