我在表单中以下列方式使用 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
以使用 GET
或 POST
请求外,我看不到解决此问题的方法;在这样做之前,您应该仔细考虑是否完全使用 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/