在由web2by构建的一个缩写程序中,我想首先验证url的有效性,如果它无效,则返回第一页并显示错误消息。这是我在控制器(mvc arch.)中的代码。但我不明白出了什么问题!
import urllib
def index():
return dict()
def random_maker():
url = request.vars.url
try:
urllib.urlopen(url)
return dict(rand_url = ''.join(random.choice(string.ascii_uppercase +
string.digits + string.ascii_lowercase) for x in range(6)),
input_url=url)
except IOError:
return index()发布于 2012-08-16 02:27:23
你不能用httplib检查http响应代码吗?如果它是200,那么页面是有效的,如果它是其他任何东西(比如404)或错误,那么它是无效的。
请看这个问题:What’s the best way to get an HTTP response code from a URL?
更新:
根据你的评论,你的问题似乎是你如何处理错误。您只是在处理IOError问题。在您的情况下,您可以通过切换到以下选项来处理所有错误:
except:
return index()您还可以通过重写http_default_error来构建自己的异常处理程序。有关详细信息,请参阅How to catch 404 error in urllib.urlretrieve。
或者您可以切换到具有特定错误的urllib2,然后可以像这样处理urllib2抛出的特定错误:
from urllib2 import Request, urlopen, URLError
req = Request('http://jfvbhsjdfvbs.com')
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
print 'URL is good!'上面的代码将返回:
We failed to reach a server.
Reason: [Errno 61] Connection refusedurllib.error应用编程接口文档中包含了每个异常类的详细信息。
我不确定如何将其插入到您的代码中,因为我不确定您到底想要做什么,但是IOError不会处理urllib抛出的异常。
https://stackoverflow.com/questions/11971369
复制相似问题