Python httplib2 Handling Exceptions

Bhavani Kannan picture Bhavani Kannan · Jul 20, 2011 · Viewed 9.7k times · Source

I have this very simple code to check if a site is up or down.

import httplib2
h = httplib2.Http()
response, content = h.request("http://www.folksdhhkjd.com")
if response.status == 200:
    print "Site is Up"
else:
    print "Site is down"

When I enter a valid URL then it properly prints Site is Up because the status is 200 as expected. But, when I enter an invalid URL, should it not print Site is down? Instead it prints an exception something like this

Traceback (most recent call last):
  File "C:\Documents and Settings\kripya\Desktop\1.py", line 3, in <module>
    response, content = h.request("http://www.folksdhhkjd.com")
  File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 1436, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 1188, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 1129, in _conn_request
    raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
ServerNotFoundError: Unable to find the server at www.folksdhhkjd.com

How can I override this exception and print my custom defined "Site is down" message? Any guidance, please?

EDIT

Also one more question... what is the difference between using

h = httplib2.Http('.cache')   

and

h = httplib2.Http()   

Answer

jlmcdonald picture jlmcdonald · Jul 20, 2011
try:
    response, content = h.request("http://www.folksdhhkjd.com")
    if response.status==200:
        print "Site is Up"
except httplib2.ServerNotFoundError:
    print "Site is Down"

The issue with your code is that if the host doesn't respond, the request doesn't return ANY status code, and so the library throws an error (I think it's a peculiarity of the library itself, doing some sort of DNS resolution before trying to make the request).