当前位置: 首页>>代码示例>>Python>>正文


Python validators.URLValidator方法代码示例

本文整理汇总了Python中django.core.validators.URLValidator方法的典型用法代码示例。如果您正苦于以下问题:Python validators.URLValidator方法的具体用法?Python validators.URLValidator怎么用?Python validators.URLValidator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.validators的用法示例。


在下文中一共展示了validators.URLValidator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate_seeds

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def validate_seeds(self, value):
        try:
            seeds = json.loads(value)
        except ValueError:
            raise serializers.ValidationError("Seeds must be a JSON encoded string.")
        if type(seeds) != list:
            raise serializers.ValidationError("Seeds must be an array of URLs.")
        validator = URLValidator()
        errors = []
        for index, x in enumerate(seeds):
            try:
                validator(x)
            except ValidationError:
                # Add index to make it easier for CodeMirror to select the right
                # line.
                errors.append({index: x})
        if errors:
            errors.insert(0, "The seeds list contains invalid urls.")
            errors.append({"list": "\n".join(seeds)})
            raise serializers.ValidationError(errors)
        return value 
开发者ID:nasa-jpl-memex,项目名称:memex-explorer,代码行数:23,代码来源:rest.py

示例2: clean

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def clean(self):
        cleaned_data = super().clean()
        data_type = cleaned_data.get("type")
        value = cleaned_data.get("url")

        if data_type:
            if data_type.validate == '1':
                try:
                    validator = URLValidator()
                    validator(value)
                except ValidationError:
                    self.add_error('url', 'Enter valid URL')

            elif data_type.validate == '2':
                try:
                    validate_email(value)
                except ValidationError:
                    self.add_error('url', 'Enter valid Email')
        else:  # data_type none
            self.add_error('type', _('This field is required'))
        return cleaned_data 
开发者ID:eventoL,项目名称:eventoL,代码行数:23,代码来源:forms.py

示例3: _extract_urls_from_comment

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def _extract_urls_from_comment(author, body, videogoal):
    for line in body.splitlines():
        urls = re.findall(
            r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
            line)
        if len(urls) > 0:
            for url in urls:
                val = URLValidator()
                try:
                    val(url)
                    text = line.replace(url, '')
                    if ':' in text:
                        text = text.split(':', 1)[0]
                    _insert_or_update_mirror(videogoal, text, url, author)
                except ValidationError:
                    pass 
开发者ID:meneses-pt,项目名称:goals.zone,代码行数:18,代码来源:goals_populator.py

示例4: __call__

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def __call__(self, value):
        try:
            super(QuickURLValidator, self).__call__(value)
        except ValidationError as e:
            # Trivial case failed. Try for possible IDN domain
            if value:
                value = smart_text(value)
                scheme, netloc, path, query, fragment = urllib.parse.urlsplit(value)
                try:
                    netloc = netloc.encode('idna') # IDN -> ACE
                except UnicodeError: # invalid domain part
                    raise e
                url = urllib.parse.urlunsplit((scheme, netloc, path, query, fragment))
                super(URLValidator, self).__call__(url)
            else:
                raise
        else:
            url = value

        if True: # self.verify_exists no longer exists, but we're doing it anyway.
            import urllib.request, urllib.error, urllib.parse
            headers = {
                "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
                "Accept-Language": "en-us,en;q=0.5",
                "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
                "Connection": "close",
                "User-Agent": 'CourSys',
            }
            try:
                req = urllib.request.Request(url, None, headers)
                u = urllib.request.urlopen(req, timeout=2)
            except ValueError:
                raise ValidationError('Enter a valid URL.', code='invalid')
            except: # urllib2.URLError, httplib.InvalidURL, etc.
                raise ValidationError('This URL appears to be a broken link.', code='invalid_link') 
开发者ID:sfu-fas,项目名称:coursys,代码行数:37,代码来源:url_validator.py

示例5: _delete_pagefile

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def _delete_pagefile(request, course_slug, page_label, kind):
    """
    Delete page/file
    """
    with django.db.transaction.atomic():
        offering = get_object_or_404(CourseOffering, slug=course_slug)
        page = get_object_or_404(Page, offering=offering, label=page_label)
        version = page.current_version()
        member = _check_allowed(request, offering, page.can_write, page.editdate())
        if not member:
            return ForbiddenResponse(request, 'Not allowed to edit this '+kind+'.')
        can_create = member.role in MEMBER_ROLES[offering.page_creators()]
        if not can_create:
            return ForbiddenResponse(request, 'Not allowed to delete pages in for this offering (must have page-creator permission).')

        from django.core.validators import URLValidator
        from django.core.exceptions import ValidationError
        val = URLValidator()

        redirect = request.POST.get('redirect', 'Index')
        #  Technically, the empty string is a valid value for the redirect because the field allows blanks.
        #  We want to avoid that when deleting a page so we need an extra check here.
        if not redirect:
            redirect = 'Index'
        url = request.build_absolute_uri(urljoin(page.get_absolute_url(), redirect))

        try:
            val(url)
        except ValidationError:
            messages.error(request, "Bad redirect URL entered. Not deleted.")
            return HttpResponseRedirect(reverse('offering:pages:edit_page', kwargs={'course_slug': course_slug, 'page_label': page.label}))

        redir_version = PageVersion(page=page, title=version.title, redirect=redirect,
                                    editor=member, comment='automatically generated on deletion')
        redir_version.set_redirect_reason('delete')
        redir_version.save()

        messages.success(request, "Page deleted and will redirect to this location.")
        return HttpResponseRedirect(urljoin(page.get_absolute_url(), redirect)) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:41,代码来源:views.py

示例6: clean

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def clean(self):
        cleaned_data = super(MainForm, self).clean()
        domain_string = cleaned_data.get('domain', '')
        if not (domain_string.startswith('http://') or domain_string.startswith('https://')):
            domain_string = 'http://%s' % domain_string
        validator = validators.URLValidator()
        try:
            validator(domain_string)
        except:
            raise forms.ValidationError('Please enter a valid URL.')
        cleaned_data['domain_base'] = urlparse(domain_string).netloc
        return cleaned_data 
开发者ID:opendata,项目名称:lmgtdfy,代码行数:14,代码来源:forms.py

示例7: test_enketo_remote_server

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def test_enketo_remote_server(self):
        if not self._running_enketo():
            raise SkipTest
        with HTTMock(enketo_mock):
            server_url = 'https://testserver.com/bob'
            form_id = "test_%s" % re.sub(re.compile("\."), "_", str(time()))
            url = enketo_url(server_url, form_id)
            self.assertIsInstance(url, basestring)
            self.assertIsNone(URLValidator()(url)) 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:11,代码来源:test_form_enter_data.py

示例8: validate_bugs

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def validate_bugs(value):
    """
    Inherits from a Built-in URLValidator
    """
    return bugs_validator(value) 
开发者ID:82Flex,项目名称:DCRM,代码行数:7,代码来源:version.py

示例9: add_city_image

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def add_city_image(request):
    """
    Add image URL to a city
    :param request:
    :return: 400 Invalid City ID or Incorrect Image URL
    :return: 200 successful
    """
    city_id = request.POST.get('city_id', None)
    image_url = request.POST.get('image_url', None)

    url_validator = URLValidator()

    if not city_id or not image_url:
        # incorrect request received
        error_message = "Missing parameters in request. Send city_id, image_url"
        return Response(error_message, status=status.HTTP_400_BAD_REQUEST)

    try:
        url_validator(image_url)
        city = City.objects.get(pk=city_id)
        city_image = CityImage(city=city, image_url=image_url)
        city_image.save()
    except ValidationError as e:
        # e is a list of error messages
        error_message = "\n".join(e)
        return Response(error_message, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        error_message = str(e)
        return Response(error_message, status=status.HTTP_400_BAD_REQUEST)

    success_message = "Successfully added new city image."
    return Response(success_message, status=status.HTTP_201_CREATED) 
开发者ID:project-travel-mate,项目名称:server,代码行数:34,代码来源:views.py

示例10: check_url

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def check_url(var_name: str, val: object) -> str:
    # First, ensure val is a string
    s = check_string(var_name, val)
    # Now, validate as URL
    validate = URLValidator()
    try:
        validate(s)
        return s
    except ValidationError:
        raise ValidationError(_('{var_name} is not a URL').format(var_name=var_name)) 
开发者ID:zulip,项目名称:zulip,代码行数:12,代码来源:validator.py

示例11: register_remote_server

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def register_remote_server(
        request: HttpRequest,
        zulip_org_id: str=REQ(str_validator=check_string_fixed_length(RemoteZulipServer.UUID_LENGTH)),
        zulip_org_key: str=REQ(str_validator=check_string_fixed_length(RemoteZulipServer.API_KEY_LENGTH)),
        hostname: str=REQ(str_validator=check_capped_string(RemoteZulipServer.HOSTNAME_MAX_LENGTH)),
        contact_email: str=REQ(str_validator=check_string),
        new_org_key: Optional[str]=REQ(str_validator=check_string_fixed_length(
            RemoteZulipServer.API_KEY_LENGTH), default=None),
) -> HttpResponse:
    # REQ validated the the field lengths, but we still need to
    # validate the format of these fields.
    try:
        # TODO: Ideally we'd not abuse the URL validator this way
        url_validator = URLValidator()
        url_validator('http://' + hostname)
    except ValidationError:
        raise JsonableError(_('{} is not a valid hostname').format(hostname))

    try:
        validate_email(contact_email)
    except ValidationError as e:
        raise JsonableError(e.message)

    remote_server, created = RemoteZulipServer.objects.get_or_create(
        uuid=zulip_org_id,
        defaults={'hostname': hostname, 'contact_email': contact_email,
                  'api_key': zulip_org_key})

    if not created:
        if remote_server.api_key != zulip_org_key:
            raise InvalidZulipServerKeyError(zulip_org_id)
        else:
            remote_server.hostname = hostname
            remote_server.contact_email = contact_email
            if new_org_key is not None:
                remote_server.api_key = new_org_key
            remote_server.save()

    return json_success({'created': created}) 
开发者ID:zulip,项目名称:zulip,代码行数:41,代码来源:views.py

示例12: _save_entry_url_sources

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def _save_entry_url_sources(request, entry_version: EntryVersion):
    """
    Save updated url sources.
    """
    source_re = r'^url-source-(\d+)-(name|url)$'

    urls_data = defaultdict(dict)  # {id -> {url: "", name: ""}
    validator = URLValidator(['http', 'https'])

    for key in filter(lambda k: re.match(source_re, k), request.POST):
        match = re.match(source_re, key)
        urls_data[match.group(1)][match.group(2)] = request.POST[key]

    entry_version.url_sources.clear()

    for url_data in urls_data.values():
        name = url_data['name']
        url = url_data['url']

        try:
            validator(url)
        except ValidationError:
            continue

        if not url:
            continue

        try:
            url_obj = URLSource.objects.get(url=url)
        except URLSource.DoesNotExist:
            url_obj = URLSource.objects.create(url=url, text=name)
        else:
            url_obj.text = name
            url_obj.save()

        url_obj.entry_versions.add(entry_version)
        url_obj.save()

    URLSource.remove_unused()

    return 
开发者ID:Palanaeum,项目名称:palanaeum,代码行数:43,代码来源:staff_views.py

示例13: url_validator

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def url_validator(compiler, scheme='http https', default_schema=None, relaxed=False):
    """
    Args:
        default_schema: 接受没有scheme的url并尝试修正
        relaxed: accept not strict url
    """
    if relaxed:
        return Compiler().compile(T.url.scheme(scheme))
    schemes = set(scheme.replace(',', ' ').split(' '))
    if default_schema and default_schema not in schemes:
        raise SchemaError('invalid default_schema {}'.format(default_schema))
    _django_validate_url = URLValidator(schemes=schemes)

    def validate(value):
        if default_schema:
            value = coerce_url(value, default_schema=default_schema)
        try:
            _django_validate_url(value)
        except ValidationError:
            # TODO: access ValidationError.messages will cause error when
            # django/i18n not setup, maybe use validators package instead
            # raise Invalid(','.join(ex.messages).rstrip('.'))
            raise Invalid('invalid or incorrect url format')
        return value

    return validate 
开发者ID:anyant,项目名称:rssant,代码行数:28,代码来源:validator.py

示例14: __init__

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
        super(URLField, self).__init__(max_length, min_length, *args, **kwargs)
        self.validators.append(validators.URLValidator()) 
开发者ID:blackye,项目名称:luscan-devel,代码行数:5,代码来源:fields.py

示例15: __init__

# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import URLValidator [as 别名]
def __init__(self, verbose_name=None, name=None, **kwargs):
        kwargs['max_length'] = kwargs.get('max_length', 200)
        CharField.__init__(self, verbose_name, name, **kwargs)
        self.validators.append(validators.URLValidator()) 
开发者ID:blackye,项目名称:luscan-devel,代码行数:6,代码来源:__init__.py


注:本文中的django.core.validators.URLValidator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。