【问题标题】:How can I check if a URL exists with Django’s validators?如何使用 Django 的验证器检查 URL 是否存在?
【发布时间】:2011-03-11 08:36:26
【问题描述】:

我想检查 django 是否存在 URL,如果存在,我想在屏幕上显示一些东西,即:

if URL_THAT_POINTS_TO_SOME_PDF exists 
     SHOW_SOMETHING

【问题讨论】:

    标签: django url url-validation


    【解决方案1】:

    见: 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")
    

    【讨论】:

      【解决方案2】:

      问题

      from django.core.validators import URLValidator 表示www.google.ro 无效。在我看来这是错误的。或者至少还不够。

      如何解决?

      线索是查看models.URLField的源代码,你会看到它使用forms.FormField作为验证器。哪个比上面的URLValidator 更多

      解决方案

      如果我想验证url 之类的http://www.google.comwww.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
      

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 我打算写一个类似的答案。您尝试了一次,但还不够。
        • @MihaiZamfir:为什么这还不够?
        【解决方案4】:

        编辑:请注意,这对 Django 1.5 以上的任何版本都不再有效

        我假设您想检查文件是否确实存在,而不是是否只有一个对象(这只是一个简单的 if 语句)

        首先,我建议您始终查看 Django 的源代码,因为您可以使用 find some great code :)

        我假设您想在模板中执行此操作。没有用于验证 URL 的内置模板标签,但您基本上可以在模板标签中使用 URLValidator 类来测试它。简单地说:

        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 文档中了解如何创建该标签,然后就可以使用了。

        希望这是你的开始。

        【讨论】:

        【解决方案5】:

        任何基于 verify_exists 参数到 django.core.validators.URLValidator 的东西都将停止与 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 请求来检查 URL — 带宽效率,当然,但某些网站(如亚马逊)响应错误(HEAD , 其中等价的 GET 会很好),这会导致 false negative results from the validator

        我还(两年内发生了很大变化)建议不要在模板中使用 urllib2 做任何事情——这完全是请求/响应周期中错误的部分,会触发潜在的长时间运行的操作:考虑一下如果 URL 确实存在,则会发生这种情况,但 DNS 问题会导致 urllib2 需要 10 秒才能解决。砰!页面加载瞬间多出 10 秒。

        我想说,目前用于制作可能长时间运行的异步任务(因此不会阻塞页面加载)的最佳实践是使用django-celerya basic tutorial 涵盖使用 pycurl 检查网站,或者您可以在 Lanyrd 上查看 how Simon Willison implemented celery tasks(幻灯片 32-41)以实现类似目的。

        【讨论】:

          【解决方案6】:
          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
          

          如果 url 前面没有像 http:// 这样的架构,则validate(value) 会失败。我想知道这是否是设计使然。

          【讨论】:

            【解决方案7】:

            又花了一个:

            从 django.core.exceptions 导入验证错误

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

            【讨论】:

              猜你喜欢
              • 2020-03-25
              • 2012-05-16
              • 1970-01-01
              • 2020-07-05
              • 2017-05-04
              • 1970-01-01
              • 1970-01-01
              • 2015-01-02
              • 2011-12-14
              相关资源
              最近更新 更多