Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python "requests" module, how do I check whether the server is down or 500?

Tags:

python

rest

http

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?

like image 428
TIMEX Avatar asked Oct 31 '14 19:10

TIMEX


1 Answers

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` 
like image 50
Thomas Orozco Avatar answered Sep 25 '22 05:09

Thomas Orozco