简体   繁体   English

Python httplib2 处理异常

[英]Python httplib2 Handling Exceptions

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.当我输入有效的 URL 时,它会正确打印站点已启动,因为状态为 200 符合预期。 But, when I enter an invalid URL, should it not print Site is down?但是,当我输入无效的 URL 时,它不应该打印站点已关闭吗? 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()   
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).您的代码的问题是,如果主机没有响应,则请求不会返回任何状态代码,因此库会引发错误(我认为这是库本身的特性,之前进行了某种 DNS 解析试图提出请求)。

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;将它检索到的内容缓存在一个名为.cache的目录中,因此如果您两次执行相同的请求,它可能不必实际获取所有内容两次; a file starting with a dot is hidden in POSIX filesystems (like on Linux).以点开头的文件隐藏在 POSIX 文件系统中(如在 Linux 上)。

h = httplib2.Http()

Doesn't cache it's results, so you have to get everything requested every time.不缓存它的结果,所以你每次都必须得到所有请求的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM