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"
当我输入有效的URL时,它会正确打印"Site is Up",因为状态为200,如预期的那样.但是,当我输入无效的URL时,是否应该不打印网站已关闭?相反,它会打印出类似这样的异常
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?
编辑
还有一个问题...使用
Also one more question... what is the difference between using
h = httplib2.Http('.cache')
和
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"
您的代码存在的问题是,如果主机不响应,则请求不会返回任何状态代码,因此库将引发错误(我认为这是库本身的特殊性,它会执行某些操作尝试提出请求之前先进行DNS解析.
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).
这篇关于Python httplib2处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!