web2py url 验证器 [英] web2py url validator

查看:26
本文介绍了web2py url 验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在由 web2by 构建的缩短器中,我想首先验证 url,如果它无效,则返回第一页并显示错误消息.这是我在控制器 (mvc arch.) 中的代码,但我不明白出了什么问题..!!

In a shorten-er built by web2by i want to validate url's first, if it's not valid goes back to the first page with an error message. this is my code in controller (mvc arch.) but i don't get what's wrong..!!

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)或错误,则无效.

Couldn't you check the http response code using httplib. If it was 200 then the page is valid, if it is anything else (like 404) or an error then it is invalid.

请参阅此问题:获取 HTTP 响应的最佳方法是什么来自 URL 的代码?

根据您的评论,您的问题似乎是您处理错误的方式.您只处理 IOError 问题.在您的情况下,您可以通过切换到:

Based on your comment it looks like your issue is how you are handling the error. You are only handling IOError issues. In your case you can either handle all errors singularly by switching to:

except:
    return index()

您还可以通过覆盖 http_default_error 来构建自己的异常处理程序.请参阅如何在 urllib.urlretrieve 中捕获 404 错误,了解更多信息信息.

You could also build your own exception handler by overriding http_default_error. See How to catch 404 error in urllib.urlretrieve for more information.

或者您可以切换到具有特定错误的 urllib2,然后您可以像这样处理 urllib2 抛出的特定错误:

Or you can switch to urllib2 which has specific errors, You can then handle the specific errors that urllib2 throws like this:

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 文档中.

The specifics of each exception class is contained in the urllib.error api documentation.

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

I am not exactly sure how to slot this into your code, because I am not sure exactly what you are trying to do, but IOError is not going to handle the exceptions thrown by urllib.

这篇关于web2py url 验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆