我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.six.moves.urllib.parse.urlparse()。
def url_replace_param(url, name, value): """ Replace a GET parameter in an URL """ url_components = urlparse(force_str(url)) params = parse_qs(url_components.query) if value is None: del params[name] else: params[name] = value return mark_safe(urlunparse([ url_components.scheme, url_components.netloc, url_components.path, url_components.params, urlencode(params, doseq=True), url_components.fragment, ]))
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
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__)
def channel_cors(sender, request, **kwargs): """ This signal checks for channel `CORS_ORIGIN_WHITELIST` settings. If the channel as a setting where the value match the Origin header the request will have the correct Access-Control-Allow-Origin on the response. """ channel = get_channel(request.channel) if channel: origin = request.META.get("HTTP_ORIGIN", "") domain = urlparse(origin).netloc if domain in channel["settings"].get("CORS_ORIGIN_WHITELIST", []): return True return False # check_request_enabled.connect(channel_cors) # Custom channel signal
def chooseRedirect(request, playground_id, sandbox_id): """ Determine whether we redirect to the playground detail or sandbox detail """ next = request.META.get('HTTP_REFERER', None) or None redirectToPlayground = True if next is not None: match = resolve(urlparse(next)[2]) if match is not None: if match.view_name.startswith("sandbox"): redirectToPlayground = False if redirectToPlayground: return HttpResponseRedirect(reverse("playground", args=[playground_id])) else: return HttpResponseRedirect(reverse("sandbox-details", args=[playground_id, sandbox_id]))
def get_build_path(self, obj): url = self.get_url(obj) if url.startswith('http'): # Multisite has absolute urls url_parsed = urlparse(url) path = url_parsed.path hostname = url_parsed.hostname if getattr(settings, 'BAKERY_MULTISITE', False): build_path = os.path.join( settings.BUILD_DIR, hostname, path[1:]) else: build_path = os.path.join(settings.BUILD_DIR, path[1:]) else: # Single site has relative urls build_path = os.path.join(settings.BUILD_DIR, url[1:]) # Make sure the (deeply) directories are created os.path.exists(build_path) or os.makedirs(build_path) # Always append index.html at the end of the path return os.path.join(build_path, 'index.html')
def test_login_evil_redirect(self): """ Make sure that if we give an URL other than our own host as the next parameter, it is replaced with the default LOGIN_REDIRECT_URL. """ # monkey patch SAML configuration settings.SAML_CONFIG = conf.create_conf( sp_host='sp.example.com', idp_hosts=['idp.example.com'], metadata_file='remote_metadata_one_idp.xml', ) response = self.client.get(reverse('saml2_login') + '?next=http://evil.com') url = urlparse(response['Location']) params = parse_qs(url.query) self.assertEqual(params['RelayState'], [settings.LOGIN_REDIRECT_URL, ])
def configure_from_settings(self, settings): # Default configuration self.charset = settings.FILE_CHARSET self.autorefresh = settings.DEBUG self.use_finders = settings.DEBUG self.static_prefix = urlparse(settings.STATIC_URL or '').path if settings.DEBUG: self.max_age = 0 # Allow settings to override default attributes for attr in self.config_attrs: settings_key = 'WHITENOISE_{0}'.format(attr.upper()) try: value = getattr(settings, settings_key) except AttributeError: pass else: value = decode_if_byte_string(value) setattr(self, attr, value) self.static_prefix = ensure_leading_trailing_slash(self.static_prefix) self.static_root = decode_if_byte_string(settings.STATIC_ROOT)
def assertURLEqual(self, url, expected, parse_qs=False): """ Given two URLs, make sure all their components (the ones given by urlparse) are equal, only comparing components that are present in both URLs. If `parse_qs` is True, then the querystrings are parsed with QueryDict. This is useful if you don't want the order of parameters to matter. Otherwise, the query strings are compared as-is. """ fields = ParseResult._fields for attr, x, y in zip(fields, urlparse(url), urlparse(expected)): if parse_qs and attr == 'query': x, y = QueryDict(x), QueryDict(y) if x and y and x != y: self.fail("%r != %r (%s doesn't match)" % (url, expected, attr))
def test_login_evil_redirect(self): """ Make sure that if we give an URL other than our own host as the next parameter, it is replaced with the default LOGIN_REDIRECT_URL. """ # monkey patch SAML configuration settings.SAML_CONFIG = conf.create_conf( sp_host='sp.example.com', idp_hosts=['idp.example.com'], metadata_file='remote_metadata_one_idp.xml', ) response = self.client.get(reverse('saml2_login') + '?next=http://evil.com') url = urlparse(response['Location']) params = parse_qs(url.query) self.assertEquals(params['RelayState'], [settings.LOGIN_REDIRECT_URL, ])
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
def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) super(StaticFilesHandler, self).__init__()
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)
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)
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)
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)