我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.http.HttpResponsePermanentRedirect()。
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 page(request, path): """Page processing view""" # ensure that path starts and ends with "/" if not path.startswith("/"): path = "/" + path # redirect to equivalent page with ending slash # if path doesn't end with slash and it's not a file name: if not path.endswith("/") and '.' not in path.split('/')[-1]: return http.HttpResponsePermanentRedirect(path + "/") matching_pages = Page.objects.all().filter(url=path) try: page_obj = matching_pages[0] except IndexError: raise http.Http404 page_processor = page_obj.get_page_processor() return page_processor.process_request(request)
def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.get_user() if user is not None: auth_login(request, user) return HttpResponsePermanentRedirect(request.session['LoginForm']) else: auth_logout(request) print(login_form.errors) return render(request, 'users/login.html', {'errors': login_form.errors}) else: login_form = LoginForm() user = None request.session['LoginForm'] = request.META.get('HTTP_REFERER', '/') return render(request, 'users/login.html')
def get(self, request, nb_path): event = Event.objects.filter(nb_path=nb_path, published=True).first() if event: return HttpResponsePermanentRedirect(reverse('view_event', args=[event.id])) group = SupportGroup.objects.filter(nb_path=nb_path, published=True).first() if group: return HttpResponsePermanentRedirect(reverse('view_group', args=[group.id])) try: nb_url = nb_path if request.META['QUERY_STRING']: nb_url = nb_url + '?' + request.META['QUERY_STRING'] try: url = self.nb_paths[nb_url] return HttpResponsePermanentRedirect(url) except KeyError: pass url = self.nb_paths[nb_path] return HttpResponsePermanentRedirect(url) except KeyError: pass return HttpResponse(status=404)
def get(request, plan_id, slug=None, template_name='plan/get.html'): '''Display the plan details.''' SUB_MODULE_NAME = 'plans' try: tp = TestPlan.objects.select_related().get(plan_id=plan_id) tp.latest_text = tp.latest_text() except ObjectDoesNotExist: raise Http404 # redirect if has a cheated slug if slug != slugify(tp.name): return HttpResponsePermanentRedirect(tp.get_absolute_url()) # Initial the case counter confirm_status_name = 'CONFIRMED' tp.run_case = tp.case.filter(case_status__name=confirm_status_name) tp.review_case = tp.case.exclude(case_status__name=confirm_status_name) context_data = { 'module': MODULE_NAME, 'sub_module': SUB_MODULE_NAME, 'test_plan': tp, } return render(request, template_name, context_data)
def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get('username', '') password = request.POST.get('password', '') # ??? authenticate ?? return user user = authenticate(username=user_name, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponsePermanentRedirect(reverse('index')) return render(request, 'login.html', {'msg': '??????'}) return render(request, 'login.html', {'msg': '??????????'}) return render(request, 'login.html', {'form_errors': login_form.errors}) #????
def roomindex(request): return HttpResponsePermanentRedirect('/1/') # room_list = Room.objects.all().order_by('name', 'description') # return render(request, 'stregsystem/roomindex.html', {'room_list': room_list})
def process_request(self, request, extra_context=None): """Redirection processing logic""" try: location = self.get_redirect_location() except: location = '/' permanent = False else: permanent = self.config.get('permanent') response_class = ( http.HttpResponsePermanentRedirect if permanent else http.HttpResponseRedirect ) return response_class(location)
def process_request(self, request): path = request.path.lstrip("/") if (self.redirect and not request.is_secure() and not any(pattern.search(path) for pattern in self.redirect_exempt)): host = self.redirect_host or request.get_host() return HttpResponsePermanentRedirect( "https://%s%s" % (host, request.get_full_path()) )
def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) if url: if self.permanent: return http.HttpResponsePermanentRedirect(url) else: return http.HttpResponseRedirect(url) else: logger.warning('Gone: %s', request.path, extra={ 'status_code': 410, 'request': request }) return http.HttpResponseGone()
def _redirect_response(redirect_to): return http.HttpResponsePermanentRedirect(redirect_to=redirect_to)
def redirect_to_article(request, year, month, day, slug): # this is a little snippet to handle URLs that are formatted the old way. article = get_object_or_404(Article, publish_date__year=year, slug=slug) return HttpResponsePermanentRedirect(article.get_absolute_url())
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 redirect_original(request, short_id): url = get_object_or_404(urls, pk=short_id) # get object, if not found return 404 error url.count += 1 url.save() return HttpResponsePermanentRedirect(url.httpurl)
def _redirect(self, request, secure): protocol = secure and "https" or "http" newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path()) if settings.DEBUG and request.method == 'POST': raise RuntimeError, \ """Django can't perform a SSL redirect while maintaining POST data. Please structure your views so that redirects only occur during GETs.""" return HttpResponsePermanentRedirect(newurl)
def process_view(self, request, view_func, view_args, view_kwargs): if not settings.DEBUG: """ only perform the redirect if not debug mode """ protocol = 'https://' if request.is_secure() else 'http://' host = get_host(request) new_url = '' try: if host in settings.CANON_URLS_TO_REWRITE: new_url = protocol + settings.CANON_URL_HOST + request.get_full_path() except AttributeError: if host != settings.CANON_URL_HOST: new_url = protocol + settings.CANON_URL_HOST + request.get_full_path() if new_url: return HttpResponsePermanentRedirect(new_url)
def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) if url: if self.permanent: return http.HttpResponsePermanentRedirect(url) else: return http.HttpResponseRedirect(url) else: logger.warning( 'Gone: %s', request.path, extra={'status_code': 410, 'request': request} ) return http.HttpResponseGone()
def process_request(self, request): try: jwt_token = request.META['HTTP_' + self.jwt_authentication_header] token_validator = TokenValidator(jwt_validator_url=self.jwt_validator_url, jwt_token=jwt_token) token_validator_response = token_validator.validate_token() if token_validator_response == UNAUTHORIZED: return HttpResponsePermanentRedirect(self.jwt_failed_redirect_url) else: request.decoded_jwt_token = token_validator_response except Exception as e: return HttpResponsePermanentRedirect(self.jwt_failed_redirect_url)
def v_post(self, request, year, month, day, pk, slug): newsitem = get_object_or_404(self.get_newsitems_for_display(), pk=pk) # Check the URL date and slug are still correct newsitem_url = newsitem.url newsitem_path = urlparse(newsitem_url, allow_fragments=True).path if urlquote(request.path) != newsitem_path: return HttpResponsePermanentRedirect(newsitem_url) # Get the newsitem to serve itself return newsitem.serve(request)
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__exact=url, sites__id__exact=site_id) except Http404: if not url.endswith('/') and settings.APPEND_SLASH: url += '/' f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=site_id) return HttpResponsePermanentRedirect('%s/' % request.path) else: raise return render_flatpage(request, f)
def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a redirect for non-404 responses. 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 http.HttpResponseGone() return http.HttpResponsePermanentRedirect(r.new_path) # No redirect was found. Return the response. return response
def redirect(request, redirect_to, tail=''): return HttpResponsePermanentRedirect(redirect_to + tail)