编程语言
首页 > 编程语言> > python-web2py URL验证器

python-web2py URL验证器

作者:互联网

在由web2by构建的简化程序中,我要验证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()

解决方法:

您无法使用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 refused

每个异常类的详细信息都包含在urllib.error api文档中.

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

标签:web2py,python,urllib
来源: https://codeday.me/bug/20191012/1901632.html