本文整理匯總了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
示例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__)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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__()
示例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
示例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
示例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, '', '', '']
)
示例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)
示例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)
示例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)
示例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