我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.APPEND_SLASH。
def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or :template:`flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.startswith('/'): url = '/' + url site_id = get_current_site(request).id try: f = get_object_or_404(FlatPage, url=url, sites=site_id) except Http404: if not url.endswith('/') and settings.APPEND_SLASH: url += '/' f = get_object_or_404(FlatPage, url=url, sites=site_id) return HttpResponsePermanentRedirect('%s/' % request.path) else: raise return render_flatpage(request, f)
def check_pattern_startswith_slash(pattern): """ Check that the pattern does not begin with a forward slash. """ regex_pattern = pattern.regex.pattern if not settings.APPEND_SLASH: # Skip check as it can be useful to start a URL pattern with a slash # when APPEND_SLASH=False. return [] if regex_pattern.startswith('/') or regex_pattern.startswith('^/'): warning = Warning( "Your URL pattern {} has a regex beginning with a '/'. Remove this " "slash as it is unnecessary. If this pattern is targeted in an " "include(), ensure the include() pattern has a trailing '/'.".format( describe_pattern(pattern) ), id="urls.W002", ) return [warning] else: return []
def clean_url(self): url = self.cleaned_data['url'] if not url.startswith('/'): raise forms.ValidationError( ugettext("URL is missing a leading slash."), code='missing_leading_slash', ) if (settings.APPEND_SLASH and ( (settings.MIDDLEWARE and 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE) or 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES) and not url.endswith('/')): raise forms.ValidationError( ugettext("URL is missing a trailing slash."), code='missing_trailing_slash', ) return url
def _check_pattern_startswith_slash(self): """ Check that the pattern does not begin with a forward slash. """ regex_pattern = self.regex.pattern if not settings.APPEND_SLASH: # Skip check as it can be useful to start a URL pattern with a slash # when APPEND_SLASH=False. return [] if (regex_pattern.startswith('/') or regex_pattern.startswith('^/')) and not regex_pattern.endswith('/'): warning = Warning( "Your URL pattern {} has a regex beginning with a '/'. Remove this " "slash as it is unnecessary. If this pattern is targeted in an " "include(), ensure the include() pattern has a trailing '/'.".format( self.describe() ), id="urls.W002", ) return [warning] else: return []
def urljoin(*segments): """Joins url segments together and appends trailing slash if required. >>> urljoin('a', 'b', 'c') u'a/b/c/' >>> urljoin('a', '//b//', 'c') u'a/b/c/' >>> urljoin('/a', '/b/', '/c/') u'/a/b/c/' >>> urljoin('/a', '') u'/a/' """ url = '/' if segments[0].startswith('/') else '' url += '/'.join(filter(None, (force_text(s).strip('/') for s in segments))) return url + '/' if settings.APPEND_SLASH else url
def clean_url(self): url = self.cleaned_data['url'] if not url.startswith('/'): raise forms.ValidationError( ugettext("URL is missing a leading slash."), code='missing_leading_slash', ) if (settings.APPEND_SLASH and 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES and not url.endswith('/')): raise forms.ValidationError( ugettext("URL is missing a trailing slash."), code='missing_trailing_slash', ) return url
def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response full_path = request.get_full_path() current_site = get_current_site(request) r = None try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if r is None and settings.APPEND_SLASH and not request.path.endswith('/'): try: r = Redirect.objects.get( site=current_site, old_path=request.get_full_path(force_append_slash=True), ) except Redirect.DoesNotExist: pass if r is not None: if r.new_path == '': return self.response_gone_class() return self.response_redirect_class(r.new_path) # No redirect was found. Return the response. return response
def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents if 'HTTP_USER_AGENT' in request.META: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(request.META['HTTP_USER_AGENT']): raise PermissionDenied('Forbidden user agent') # Check for a redirect based on settings.PREPEND_WWW host = request.get_host() must_prepend = settings.PREPEND_WWW and host and not host.startswith('www.') redirect_url = ('%s://www.%s' % (request.scheme, host)) if must_prepend else '' # Check if a slash should be appended if self.should_redirect_with_slash(request): path = self.get_full_path_with_slash(request) else: path = request.get_full_path() # Return a redirect if necessary if redirect_url or path != request.get_full_path(): redirect_url += path return self.response_redirect_class(redirect_url)
def should_redirect_with_slash(self, request): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if settings.APPEND_SLASH and not request.get_full_path().endswith('/'): urlconf = getattr(request, 'urlconf', None) return ( not urlresolvers.is_valid_path(request.path_info, urlconf) and urlresolvers.is_valid_path('%s/' % request.path_info, urlconf) ) return False
def process_response(self, request, response): language = translation.get_language() language_from_path = translation.get_language_from_path(request.path_info) if (response.status_code == 404 and not language_from_path and self.is_language_prefix_patterns_used): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) path_needs_slash = ( not path_valid and ( settings.APPEND_SLASH and not language_path.endswith('/') and is_valid_path('%s/' % language_path, urlconf) ) ) if path_valid or path_needs_slash: script_prefix = get_script_prefix() # Insert language after the script prefix and before the # rest of the URL language_url = request.get_full_path(force_append_slash=path_needs_slash).replace( script_prefix, '%s%s/' % (script_prefix, language), 1 ) return self.response_redirect_class(language_url) if not (self.is_language_prefix_patterns_used and language_from_path): patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def process_response(request, response): if response.status_code != 404: return response full_path = request.get_full_path() redirect = None try: redirect = Redirect.objects.get(old_path=full_path) except Redirect.DoesNotExist: pass if settings.APPEND_SLASH and not request.path.endswith('/'): # Try appending a trailing slash. path_len = len(request.path) full_path = full_path[:path_len] + '/' + full_path[path_len:] try: redirect = Redirect.objects.get(old_path=full_path) except Redirect.DoesNotExist: pass if redirect is None: return response if redirect.new_path == '': return http.HttpResponseGone() redirect.last_usage = now() redirect.save() if redirect.permanent: return http.HttpResponsePermanentRedirect(redirect.new_path) else: return http.HttpResponseRedirect(redirect.new_path)
def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response full_path = request.get_full_path() current_site = get_current_site(request) r = None try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if settings.APPEND_SLASH and not request.path.endswith('/'): # Try appending a trailing slash. path_len = len(request.path) full_path = full_path[:path_len] + '/' + full_path[path_len:] try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if r is not None: if r.new_path == '': return self.response_gone_class() return self.response_redirect_class(r.new_path) # No redirect was found. Return the response. return response
def process_response(self, request, response): language = translation.get_language() language_from_path = translation.get_language_from_path(request.path_info) if (response.status_code == 404 and not language_from_path and self.is_language_prefix_patterns_used()): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) if (not path_valid and settings.APPEND_SLASH and not language_path.endswith('/')): path_valid = is_valid_path("%s/" % language_path, urlconf) if path_valid: script_prefix = get_script_prefix() language_url = "%s://%s%s" % ( request.scheme, request.get_host(), # insert language after the script prefix and before the # rest of the URL request.get_full_path().replace( script_prefix, '%s%s/' % (script_prefix, language), 1 ) ) return self.response_redirect_class(language_url) if not (self.is_language_prefix_patterns_used() and language_from_path): patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response