web2py url有效

2024-09-29 07:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在web2by构建的shorten er中,我想验证url的第一个,如果它无效,则返回第一个页面并显示错误消息。这是我在控制器(mvc架构)中的代码,但我不知道哪里出了问题。。!!在

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

Tags: 消息urlstringindexreturndef错误shorten
1条回答
网友
1楼 · 发布于 2024-09-29 07:20:43

你不能用httplib检查http响应代码吗。如果它是无效的,那么它是无效的。在

看这个问题: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抛出的特定错误,如下所示:

^{pr2}$

上面的代码将返回:

We failed to reach a server.
Reason:  [Errno 61] Connection refused

每个异常类的细节包含在urllib.错误api文档。在

我不太确定如何将其插入到代码中,因为我不确定您到底要做什么,但是IOError不会处理urllib引发的异常。在

相关问题 更多 >