2010-07-03 74 views

回答

45

编辑:请注意,这已不再适用于上述的Django的任何版本1.5

我假设你要检查,如果该文件确实存在,而不是是否存在只是一个对象(这仅仅是一个简单的if语句)

首先,我会建议一直在寻找通过Django的源代码,因为你会find some great code,你可以使用:)

我假设你想在一个模板中做到这一点。没有内置模板标签来验证URL,但您可以使用该模板标签中的该类来测试它。简单地说:

from django.core.validators import URLValidator 
from django.core.exceptions import ValidationError 

validate = URLValidator(verify_exists=True) 
try: 
    validate('http://www.somelink.com/to/my.pdf') 
except ValidationError, e: 
    print e 

URLValidator类将吐出ValidationError时,它无法打开链接。它使用urllib2实际打开请求,所以它不仅仅使用基本的正则表达式检查(但它也是这样做的)。

你可以把它放到一个自定义模板标签中,你会发现如何在django文档中创建然后离开你。

希望这是你的开始。

+19

'verify_exists'是[不再安全(https://docs.djangoproject.com/en/1.4/ref /models/fields/#django.db.models.URLField.verify_exists)的原因,并已在Django 1.5 – Yohann 2013-04-12 15:57:17

+0

中删除,因为django 1.5,verify_exists参数已被弃用/删除,您不能再验证是否存在url,它现在只是一个简单的正则表达式匹配一个有效的url – 2013-05-23 06:15:31

+0

[在互联网档案中的警告链接](https://web.archive.org/ web/20150907152504/https://docs.djangoproject.com/en/1.4/ref/models/fields/#django.db.models.URLField.verify_exists) – luckydonald 2016-09-21 15:59:39

2

花了一个额外的:

从django.core.exceptions导入ValidationError

它为我工作。只是说; 0)

1
from django.core.validators import URLValidator 
from django.core.exceptions import ValidationError 

validate = URLValidator(verify_exists=True)  
value = request.GET.get('url', None) 

if value:   
    try: 
     validate(value) 
    except ValidationError, e: 
     print e 

validate(value)如果URL不喜欢http://架构preceeded失败。我想知道这是否是设计。基于该verify_exists参数django.core.validators.URLValidator

4

任何将停止使用Django 1.5工作 - the documentation帮忙,只字未提这一点,但source code表明,使用1.4(最新的稳定版本),其机制导致DeprecationWarning(你会见it has been removed completely in the development version):

if self.verify_exists: 
    import warnings 
    warnings.warn(
     "The URLField verify_exists argument has intractable security " 
     "and performance issues. Accordingly, it has been deprecated.", 
     DeprecationWarning 
     ) 

也有一些奇怪的怪癖用这种方法涉及到的事实,它采用了HEAD请求,然后检查网址 - 高带宽的,肯定的,但一些网站(如亚马逊)与回应错误(到HEAD,其中equ价格GET会很好),这导致false negative results from the validator

我也会(在两年内改变很多)建议不要在模板中使用urllib2做任何事情 - 这完全是请求/响应周期中触发潜在的长时间运行的错误部分:考虑发生了什么如果URL确实存在,但DNS问题会导致urllib2需要10秒才能解决问题。 BAM!即时加载页面10秒。

我想说的是,使这种异步(并因此不阻止页面加载)等可能长时间运行的任务的最佳做法是使用django-celery;有a basic tutorial涵盖了使用pycurl来检查网站,或者您可以在Lanyrd上查看how Simon Willison implemented celery tasks(幻灯片32-41)以获得相似的目的。

0

我还没有在这里看到答案。这可能对别人有帮助。

from django import forms 
f = forms.URLField() 
try: 
    f.clean(http://example.com) 
    print "valid url" 
except: 
    print "invalid url" 
+0

我打算做类似的事情。你有一个很好的尝试,但这还不够。 – 2017-01-19 16:16:59

1

问题

from django.core.validators import URLValidatorwww.google.ro是无效的。我的观点是错误的。或者至少不够。

如何解决?

线索要查看models.URLField的源代码,您将看到它使用forms.FormField作为验证程序。这确实超过URLValidator从上面

解决方案

如果我想验证一个urlhttp://www.google.com或类似www.google.ro,我会做到以下几点:

从django.forms导入URLField

def validate_url(url): 
    url_form_field = URLField() 
    try: 
     url = url_form_field.clean(url) 
    except ValidationError: 
     return False 
    return True 

我发现这很有用。也许它可以帮助别人。

0

参见: http://www.agmweb.ca/2009-04-19-django-urlpatterns---its-more-than-just-urls/

在Django 1.10我现在使用:

from django.core.urlresolvers import RegexURLResolver, Resolver404 

if 'next' in request.GET.keys(): 
    n = request.GET["next"].strip('/') + "/" 
    resolver = RegexURLResolver(r'', urls) 
    try: 
     callback, callback_args, callback_kwargs = resolver.resolve(n) 
     return HttpResponseRedirect(str(request.GET["next"])) 
    except Resolver404: 
     raise PermissionDenied("This page is not available") 
相关问题