Python httplib2 Handling Exceptions

2019-03-16 22:03发布

问题:

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()   

回答1:

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).



回答2:

h = httplib2.Http('.cache')   

Caches the stuff it retrieves in a directory called .cache so if you do the same request twice it might not have to actually get everything twice; a file starting with a dot is hidden in POSIX filesystems (like on Linux).

h = httplib2.Http()

Doesn't cache it's results, so you have to get everything requested every time.