python - django URLValidator 产生虚假错误

标签 python django url-validation

我在表单中以下列方式使用 Django URLValidator:

def clean_url(self):
    validate = URLValidator(verify_exists=True)
    url = self.cleaned_data.get('url')

    try:
        logger.info(url)
        validate(url)
    except ValidationError, e:
        logger.info(e)
        raise forms.ValidationError("That website does not exist. Please try again.")

    return self.cleaned_data.get('url')

它似乎适用于某些 url,但对于某些有效的 url,它会失败。我可以用 http://www.amazon.com/ 检查它失败了(这显然是不正确的)。它通过 http://www.cisco.com/ .是否有任何虚假错误的原因?

最佳答案

the source for URLValidator ;如果您指定 check_exists,它会向 URL 发出一个 HEAD 请求以检查它是否有效:

req = urllib2.Request(url, None, headers)
req.get_method = lambda: 'HEAD'
...
opener.open(req, timeout=10)

尝试自己向 Amazon 发出 HEAD 请求,您会发现问题所在:

carl@chaffinch:~$ HEAD http://www.amazon.com
405 MethodNotAllowed
Date: Mon, 13 Aug 2012 18:50:56 GMT
Server: Server
Vary: Accept-Encoding,User-Agent
Allow: POST, GET
...

除了猴子修补或以其他方式扩展 URLValidator 以使用 GETPOST 请求外,我看不到解决此问题的方法;在这样做之前,您应该仔细考虑是否完全使用 check_exists(如果没有它,这个问题应该会消失)。正如 core/validators.py 本身所说,

"The URLField verify_exists argument has intractable security and performance issues. Accordingly, it has been deprecated."

你会发现开发中的Django版本确实完全抛弃了这个特性。

关于python - django URLValidator 产生虚假错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940288/

相关文章:

python - np.searchsorted() 背后有一个有趣的算法吗?

python - Django 空表单字段验证不适用于干净的方法

php - 检查 Shopify 中是否存在 url

java - 检查图像 URL 是否指向实际图像。 URL 中的空格会导致问题

php - 通过url防止xss攻击(PHP)

python - 如何取消选择在kivy filechooser ListView 中选择的多个文件

python - 如何用numpy中的索引索引数组?

python - 奇怪 "ModuleNotFoundErrior no module named iexfinance"

django - 序列化器返回对象而不是字段

django - 从守护进程收到的截断或过大的响应头