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


Python parse.urlparse方法代码示例

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


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

示例1: redirect_to_login

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def redirect_to_login(next, login_url=None,
                      redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Redirects the user to the login page, passing the given 'next' page
    """
    resolved_url = resolve_url(login_url or settings.LOGIN_URL)

    login_url_parts = list(urlparse(resolved_url))
    if redirect_field_name:
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring[redirect_field_name] = next
        login_url_parts[4] = querystring.urlencode(safe='/')

    return HttpResponseRedirect(urlunparse(login_url_parts))


# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:24,代码来源:views.py

示例2: __init__

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def __init__(self, *args, **kwargs):
        super(ProxyView, self).__init__(**kwargs)

        self._parsed_url = urlparse(self.upstream)

        if self._parsed_url.scheme not in ('http', 'https'):
            raise InvalidUpstream(ERRORS_MESSAGES['upstream-no-scheme'] % self.upstream)

        self._rewrite = []

        for from_pattern, to_pattern in self.rewrite:
            from_re = re.compile(from_pattern)
            self._rewrite.append((from_re, to_pattern))

        self.http = HTTP_POOLS
        self.log = logging.getLogger(__name__) 
开发者ID:danpoland,项目名称:drf-reverse-proxy,代码行数:18,代码来源:views.py

示例3: is_ignorable_request

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def is_ignorable_request(self, request, uri, domain, referer):
        """
        Return True if the given request *shouldn't* notify the site managers
        according to project settings or in three specific situations:
         - If the referer is empty.
         - If a '?' in referer is identified as a search engine source.
         - If the referer is equal to the current URL, ignoring the scheme
           (assumed to be a poorly implemented bot).
        """
        if not referer:
            return True

        if not self.is_internal_request(domain, referer) and '?' in referer:
            return True

        parsed_referer = urlparse(referer)
        if parsed_referer.netloc in ['', domain] and parsed_referer.path == uri:
            return True

        return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS) 
开发者ID:drexly,项目名称:openhgsenti,代码行数:22,代码来源:common.py

示例4: get_tag_uri

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def get_tag_uri(url, date):
    """
    Creates a TagURI.

    See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
    """
    bits = urlparse(url)
    d = ''
    if date is not None:
        d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d')
    return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:13,代码来源:feedgenerator.py

示例5: __init__

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def __init__(self, redirect_to, *args, **kwargs):
        parsed = urlparse(force_text(redirect_to))
        if parsed.scheme and parsed.scheme not in self.allowed_schemes:
            raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
        super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
        self['Location'] = iri_to_uri(redirect_to) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:8,代码来源:response.py

示例6: generic

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def generic(self, method, path, data='',
                content_type='application/octet-stream', secure=False,
                **extra):
        """Constructs an arbitrary HTTP request."""
        parsed = urlparse(path)
        data = force_bytes(data, settings.DEFAULT_CHARSET)
        r = {
            'PATH_INFO': self._get_path(parsed),
            'REQUEST_METHOD': str(method),
            'SERVER_PORT': str('443') if secure else str('80'),
            'wsgi.url_scheme': str('https') if secure else str('http'),
        }
        if data:
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE': str(content_type),
                'wsgi.input': FakePayload(data),
            })
        r.update(extra)
        # If QUERY_STRING is absent or empty, we want to extract it from the URL.
        if not r.get('QUERY_STRING'):
            query_string = force_bytes(parsed[4])
            # WSGI requires latin-1 encoded strings. See get_path_info().
            if six.PY3:
                query_string = query_string.decode('iso-8859-1')
            r['QUERY_STRING'] = query_string
        return self.request(**r) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:29,代码来源:client.py

示例7: add_preserved_filters

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def add_preserved_filters(context, url, popup=False, to_field=None):
    opts = context.get('opts')
    preserved_filters = context.get('preserved_filters')

    parsed_url = list(urlparse(url))
    parsed_qs = dict(parse_qsl(parsed_url[4]))
    merged_qs = dict()

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/%s' % url.partition(get_script_prefix())[2]
        try:
            match = resolve(match_url)
        except Resolver404:
            pass
        else:
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            if changelist_url == current_url and '_changelist_filters' in preserved_filters:
                preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters']))

        merged_qs.update(preserved_filters)

    if popup:
        from django.contrib.admin.options import IS_POPUP_VAR
        merged_qs[IS_POPUP_VAR] = 1
    if to_field:
        from django.contrib.admin.options import TO_FIELD_VAR
        merged_qs[TO_FIELD_VAR] = to_field

    merged_qs.update(parsed_qs)

    parsed_url[4] = urlencode(merged_qs)
    return urlunparse(parsed_url) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:37,代码来源:admin_urls.py

示例8: __init__

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def __init__(self, application):
        self.application = application
        self.base_url = urlparse(self.get_base_url())
        super(StaticFilesHandler, self).__init__() 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:6,代码来源:handlers.py

示例9: permission_required

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    this is analog to django's builtin ``permission_required`` decorator, but
    improved to check per slug ACLRules and default permissions for
    anonymous and logged in users

    if there is a rule affecting a slug, the user needs to be part of the
    rule's allowed users. If there isn't a matching rule, defaults permissions
    apply.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):

            if check_perms(perms, request.user, kwargs['slug'], raise_exception=raise_exception):
                return view_func(request, *args, **kwargs)
            if is_authenticated(request.user):
                if WALIKI_RENDER_403:
                    return render(request, 'waliki/403.html', kwargs, status=403)
                else:
                    raise PermissionDenied

            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(login_url or settings.LOGIN_URL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view

    return decorator 
开发者ID:mgaitan,项目名称:waliki,代码行数:42,代码来源:acl.py

示例10: session_passes_test

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def session_passes_test(test_func, fail_url,
                        redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the session passes the given test,
    redirecting to the choice page if necessary. The test should be a callable
    that takes the session object and returns True if the session passes. It's
    nearly a carbon copy of django.contrib.auth.decorators.user_passes_test.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.session):
                return view_func(request, *args, **kwargs)

            path = request.build_absolute_uri()
            resolved_url = resolve_url(fail_url)

            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.

            scheme, netloc = urlparse(resolved_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not scheme or scheme == current_scheme) and
                    (not netloc or netloc == current_netloc)):
                path = request.get_full_path()

            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_url, redirect_field_name)

        return _wrapped_view
    return decorator 
开发者ID:SaturdayNeighborhoodHealthClinic,项目名称:osler,代码行数:35,代码来源:decorators.py

示例11: url_to_template

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def url_to_template(self, view_name, request, template_name):
        resolver = urlresolvers.get_resolver(None)
        info = resolver.reverse_dict[view_name]

        path_template = info[0][0][0]
        # FIXME: what happens when URL has more than one dynamic values?
        # e.g. nested relations: manufacturer/%(id)s/cars/%(card_id)s
        path = path_template % {info[0][0][1][0]: '{%s}' % template_name}

        parsed_url = urlparse(request.build_absolute_uri())

        return urlunparse(
            [parsed_url.scheme, parsed_url.netloc, path, '', '', '']
        ) 
开发者ID:kevin-brown,项目名称:drf-json-api,代码行数:16,代码来源:renderers.py

示例12: is_ignorable_request

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def is_ignorable_request(self, request, uri, domain, referer):
        """
        Return True if the given request *shouldn't* notify the site managers
        according to project settings or in situations outlined by the inline
        comments.
        """
        # The referer is empty.
        if not referer:
            return True

        # APPEND_SLASH is enabled and the referer is equal to the current URL
        # without a trailing slash indicating an internal redirect.
        if settings.APPEND_SLASH and uri.endswith('/') and referer == uri[:-1]:
            return True

        # A '?' in referer is identified as a search engine source.
        if not self.is_internal_request(domain, referer) and '?' in referer:
            return True

        # The referer is equal to the current URL, ignoring the scheme (assumed
        # to be a poorly implemented bot).
        parsed_referer = urlparse(referer)
        if parsed_referer.netloc in ['', domain] and parsed_referer.path == uri:
            return True

        return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS) 
开发者ID:Yeah-Kun,项目名称:python,代码行数:28,代码来源:common.py

示例13: __init__

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def __init__(self, redirect_to, *args, **kwargs):
        super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
        self['Location'] = iri_to_uri(redirect_to)
        parsed = urlparse(force_text(redirect_to))
        if parsed.scheme and parsed.scheme not in self.allowed_schemes:
            raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme) 
开发者ID:Yeah-Kun,项目名称:python,代码行数:8,代码来源:response.py

示例14: generic

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def generic(self, method, path, data='',
                content_type='application/octet-stream', secure=False,
                **extra):
        """Constructs an arbitrary HTTP request."""
        parsed = urlparse(force_str(path))
        data = force_bytes(data, settings.DEFAULT_CHARSET)
        r = {
            'PATH_INFO': self._get_path(parsed),
            'REQUEST_METHOD': str(method),
            'SERVER_PORT': str('443') if secure else str('80'),
            'wsgi.url_scheme': str('https') if secure else str('http'),
        }
        if data:
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE': str(content_type),
                'wsgi.input': FakePayload(data),
            })
        r.update(extra)
        # If QUERY_STRING is absent or empty, we want to extract it from the URL.
        if not r.get('QUERY_STRING'):
            query_string = force_bytes(parsed[4])
            # WSGI requires latin-1 encoded strings. See get_path_info().
            if six.PY3:
                query_string = query_string.decode('iso-8859-1')
            r['QUERY_STRING'] = query_string
        return self.request(**r) 
开发者ID:Yeah-Kun,项目名称:python,代码行数:29,代码来源:client.py

示例15: user_passes_test

# 需要导入模块: from django.utils.six.moves.urllib import parse [as 别名]
# 或者: from django.utils.six.moves.urllib.parse import urlparse [as 别名]
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator 
开发者ID:drexly,项目名称:openhgsenti,代码行数:28,代码来源:decorators.py


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