Python django.http.HttpResponsePermanentRedirect() Examples

The following are 30 code examples of django.http.HttpResponsePermanentRedirect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.http , or try the search function .
Example #1
Source File: middleware.py    From simonwillisonblog with Apache License 2.0 6 votes vote down vote up
def redirect_middleware(get_response):
    def middleware(request):
        path = request.path.lstrip('/')
        redirects = list(Redirect.objects.filter(
            domain=request.get_host(),
            # We redirect on either a path match or a '*'
            # record existing for this domain
            path__in=(path, '*')
        ))
        # A non-star redirect always takes precedence
        non_star = [r for r in redirects if r.path != '*']
        if non_star:
            return HttpResponsePermanentRedirect(non_star[0].target)
        # If there's a star redirect, build path and redirect to that
        star = [r for r in redirects if r.path == '*']
        if star:
            new_url = star[0].target + path
            if request.META['QUERY_STRING']:
                new_url += '?' + request.META['QUERY_STRING']
            return HttpResponsePermanentRedirect(new_url)
        # Default: no redirects, just get on with it:
        return get_response(request)

    return middleware 
Example #2
Source File: views.py    From WCnife with MIT License 6 votes vote down vote up
def uploadFile(request):
    if request.method == 'POST':
        url = request.session.get("url")
        pwd = request.session.get("pwd")
        s = SendCode(url=url, pwd=pwd)
        newfile = request.FILES.get("newfile")
        now_filepath = request.session.get('now_path')
        path = now_filepath.split('/')[-1]
        filename = newfile.name
        filepath = now_filepath + "/" + filename
        content = ""
        for chunk in newfile.chunks():
            content = chunk.hex()
        res = s.uploadFile(filepath, content)
        return JsonResponse({"status": res, "path": path})
    else:
        return HttpResponsePermanentRedirect("/") 
Example #3
Source File: views.py    From WCnife with MIT License 6 votes vote down vote up
def createFile(request):
    if request.method == 'POST':
        url = request.session.get("url")
        pwd = request.session.get("pwd")
        s = SendCode(url=url, pwd=pwd)
        now_filepath = request.session.get('now_path')
        path = now_filepath.split('/')[-1]
        filename = request.POST.get('filename')
        content = request.POST.get('content')
        if content is None:
            content = ''
        filepath = now_filepath + '/' + filename
        res = s.createFile(filepath, content)
        return JsonResponse({"status": res, "path": path})
    else:
        return HttpResponsePermanentRedirect("/") 
Example #4
Source File: categories.py    From tramcar with MIT License 6 votes vote down vote up
def categories_show(request, category_id, slug=None):
    category = get_object_or_404(
                   Category,
                   pk=category_id,
                   site_id=get_current_site(request).id
    )

    if slug is None:
        return HttpResponsePermanentRedirect(category.get_absolute_url())

    jobs = Job.objects.filter(site_id=get_current_site(request).id) \
                      .filter(category_id=category_id) \
                      .filter(paid_at__isnull=False) \
                      .filter(expired_at__isnull=True) \
                      .order_by('-paid_at')
    form = SubscribeForm()
    meta_desc = 'Browse a list of all active %s jobs' % category.name
    feed_url = reverse('categories_feed', args=(category.id, category.slug(),))
    title = '%s Jobs' % category.name
    context = {'meta_desc': meta_desc,
               'link_rss': feed_url,
               'title': title,
               'form': form,
               'jobs': jobs}
    return render(request, 'job_board/jobs_index.html', context) 
Example #5
Source File: views.py    From python2017 with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: views.py    From django_OA with GNU General Public License v3.0 6 votes vote down vote up
def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get("username", "")
            pass_word = request.POST.get("password", "")
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponsePermanentRedirect(reverse('index'))
                else:
                    return render(request, "user_login.html", {"msg": "邮箱未激活"})
            else:
                return render(request, "user_login.html", {"msg": "用户名或密码错误"})
        else:
            return render(request, "user_login.html", {"login_form": login_form}) 
Example #7
Source File: views.py    From nyc-councilmatic with MIT License 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        slug = self.kwargs['slug']

        try:
            bill = self.model.objects.get(slug=slug)
            response = super().dispatch(request, *args, **kwargs)
        except NYCBill.DoesNotExist:
            bill = None

        if bill is None:
            try:
                bill = self.model.objects.get(slug__startswith=slug)
                response = HttpResponsePermanentRedirect(reverse('bill_detail', args=[bill.slug]))
            except NYCBill.DoesNotExist:
                try: 
                    one, two, three, four = slug.split('-')
                    short_slug = slug.replace('-' + four, '')
                    bill = self.model.objects.get(slug__startswith=short_slug)
                    response = HttpResponsePermanentRedirect(reverse('bill_detail', args=[bill.slug]))
                except:
                    response = HttpResponseNotFound()

        return response 
Example #8
Source File: views.py    From waliki with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def detail(request, slug, raw=False):

    slug = slug.strip('/')

    # handle redirects first
    try:
        redirect = Redirect.objects.get(old_slug=slug)      # noqa
        if redirect.status_code == 302:
            return HttpResponseRedirect(redirect.get_absolute_url())
        return HttpResponsePermanentRedirect(redirect.get_absolute_url())
    except Redirect.DoesNotExist:
        pass

    try:
        page = Page.objects.get(slug=slug)
    except Page.DoesNotExist:
        page = None
    if raw and page:
        return HttpResponse(page.raw, content_type='text/plain; charset=utf-8')
    elif raw:
        raise Http404

    context = {'page': page, 'slug': slug}
    return render(request, 'waliki/detail.html', context) 
Example #9
Source File: views.py    From bioforum with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: views.py    From nyc-councilmatic with MIT License 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        slug = self.kwargs['slug']

        try:
            committee = self.model.objects.get(slug=slug)
            response = super().dispatch(request, *args, **kwargs)
        except Organization.DoesNotExist:
            committee = None

        if committee is None:
            try:
                slug = slug.replace(',', '').replace('\'', '')
                committee = self.model.objects.get(slug__startswith=slug)
                response = HttpResponsePermanentRedirect(reverse('committee_detail', args=[committee.slug]))
            except Organization.DoesNotExist:
                response = HttpResponseNotFound()

        return response 
Example #11
Source File: middleware.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def process_request(self, request):
        response = super().process_request(request)
        if response is not None:
            assert type(response) is http.HttpResponsePermanentRedirect
            patch_cache_control(response, public=True, max_age=settings.HTTPS_REDIRECT_CACHE_TIME)

            # Pull out just the HTTP headers from the rest of the request meta
            headers = {
                key.lstrip("HTTP_"): value
                for (key, value) in request.META.items()
                if key.startswith("HTTP_") or key == "CONTENT_TYPE" or key == "CONTENT_LENGTH"
            }

            logger.debug(
                f"Served HTTP to HTTPS redirect for {request.path}",
                extra={
                    "code": DEBUG_HTTP_TO_HTTPS_REDIRECT,
                    "method": request.method,
                    "body": request.body.decode("utf-8"),
                    "path": request.path,
                    "headers": headers,
                },
            )
        return response 
Example #12
Source File: views.py    From anytask with MIT License 6 votes vote down vote up
def activate(request, activation_key):
    context = {'info_title': _(u'oshibka')}
    user, user_info = AdmissionRegistrationProfile.objects.activate_user(activation_key)
    if user:
        if user_info:
            set_user_info(user, json.loads(user_info))

        contest_id = contest_register(user)
        if contest_id:
            return HttpResponsePermanentRedirect(settings.CONTEST_URL + 'contest/' + str(contest_id))
        else:
            context['info_text'] = _(u'oshibka_registracii_v_contest')
    else:
        context['info_text'] = _(u'nevernyy_kod_aktivatsii')

    return render(request, 'info_page.html', context) 
Example #13
Source File: views.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: views.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get("username", "")
            pass_word = request.POST.get("password", "")
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponsePermanentRedirect(reverse('index'))
                else:
                    return render(request, "user_login.html", {"msg": "邮箱未激活"})
            else:
                return render(request, "user_login.html", {"msg": "用户名或密码错误"})
        else:
            return render(request, "user_login.html", {"login_form": login_form}) 
Example #15
Source File: viste.py    From jorvik with GNU General Public License v3.0 6 votes vote down vote up
def serve_protected_file(request, persona, pk):
    """
    Restituisce il file e incrementa il numero di downloads
    """
    try:
        file_obj = File.objects.get(pk=int(pk))
        file_obj.incrementa_downloads()
    except File.DoesNotExist:
        raise Http404('File not found')
    if file_obj.url_documento:
        return HttpResponsePermanentRedirect(file_obj.url_documento)
    if not file_obj.has_read_permission(request):
        if settings.DEBUG:
            raise PermissionDenied
        else:
            raise Http404('File not found')
    return server.serve(request, file_obj=file_obj.file, save_as=True) 
Example #16
Source File: views.py    From Spirit with MIT License 5 votes vote down vote up
def detail(request, pk, slug):
    category = get_object_or_404(
        Category.objects.visible(),
        pk=pk)

    if category.slug != slug:
        return HttpResponsePermanentRedirect(category.get_absolute_url())

    subcategories = (
        Category.objects
        .visible()
        .children(parent=category))

    topics = (
        Topic.objects
        .unremoved()
        .with_bookmarks(user=request.user)
        .for_category(category=category)
        .order_by('-is_globally_pinned', '-is_pinned', '-last_active')
        .select_related('category'))

    topics = yt_paginate(
        topics,
        per_page=config.topics_per_page,
        page_number=request.GET.get('page', 1)
    )

    return render(
        request=request,
        template_name='spirit/category/detail.html',
        context={
            'category': category,
            'subcategories': subcategories,
            'topics': topics}) 
Example #17
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
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() 
Example #18
Source File: views.py    From Spirit with MIT License 5 votes vote down vote up
def detail(request, topic_id, slug):
    topic_private = get_object_or_404(
        TopicPrivate.objects.select_related('topic'),
        topic_id=topic_id,
        user=request.user)
    topic = topic_private.topic

    if topic.slug != slug:
        return HttpResponsePermanentRedirect(topic.get_absolute_url())

    topic_viewed(request=request, topic=topic)

    comments = (
        Comment.objects
        .for_topic(topic=topic)
        .with_likes(user=request.user)
        .with_polls(user=request.user)
        .order_by('date'))

    comments = paginate(
        comments,
        per_page=config.comments_per_page,
        page_number=request.GET.get('page', 1)
    )

    return render(
        request=request,
        template_name='spirit/topic/private/detail.html',
        context={
            'topic': topic,
            'topic_private': topic_private,
            'comments': comments,}) 
Example #19
Source File: security.py    From python with Apache License 2.0 5 votes vote down vote up
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())
            ) 
Example #20
Source File: views.py    From Spirit with MIT License 5 votes vote down vote up
def detail(request, pk, slug):
    topic = Topic.objects.get_public_or_404(pk, request.user)

    if topic.slug != slug:
        return HttpResponsePermanentRedirect(topic.get_absolute_url())

    utils.topic_viewed(request=request, topic=topic)

    comments = (
        Comment.objects
        .for_topic(topic=topic)
        .with_likes(user=request.user)
        .with_polls(user=request.user)
        .order_by('date'))

    comments = paginate(
        comments,
        per_page=config.comments_per_page,
        page_number=request.GET.get('page', 1))

    return render(
        request=request,
        template_name='spirit/topic/detail.html',
        context={
            'topic': topic,
            'comments': comments}) 
Example #21
Source File: base.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        url = self.get_redirect_url(**kwargs)
        if url:
            if self.permanent:
                return http.HttpResponsePermanentRedirect(url)
            else:
                return http.HttpResponseRedirect(url)
        else:
            logger.warning('Gone: %s', self.request.path,
                        extra={
                            'status_code': 410,
                            'request': self.request
                        })
            return http.HttpResponseGone() 
Example #22
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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() 
Example #23
Source File: views.py    From nyc-councilmatic with MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        slug = self.kwargs['slug']

        try:
            person = self.model.objects.get(slug=slug)
            response = super().dispatch(request, *args, **kwargs)
        except Person.DoesNotExist:
            person = None

        if person is None:
            person_name = slug.replace('-', ' ')
            try:
                slug = slug.replace(',', '').replace('\'', '').replace('--', '-')
                person = self.model.objects.get(slug__startswith=slug)
                response = HttpResponsePermanentRedirect(reverse('person', args=[person.slug]))

            except Person.MultipleObjectsReturned:
                person_name = slug.replace('-', ' ').replace('.', '')
                # If duplicate person has middle initial.
                if re.match(r'\w+[\s.-]\w+[\s.-]\w+', slug) is not None:
                    person_name = re.sub(r'(\w+\s\w+)(\s\w+)', r'\1.\2', person_name)
                person = self.model.objects.get(name__iexact=person_name)
                response = HttpResponsePermanentRedirect(reverse('person', args=[person.slug]))
            except Person.DoesNotExist:
                response = HttpResponseNotFound()

        return response 
Example #24
Source File: security.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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())
            ) 
Example #25
Source File: views.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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) 
Example #26
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
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() 
Example #27
Source File: security.py    From python2017 with MIT License 5 votes vote down vote up
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())
            ) 
Example #28
Source File: link_views.py    From cccatalog-api with MIT License 5 votes vote down vote up
def get(self, request, path, format=None):
        """
        Given a shortened URL path, such as 'zb3k0', resolve the full URL
        and redirect the caller.
        """
        try:
            link_instance = ShortenedLink.objects.get(shortened_path=path)
        except ShortenedLink.DoesNotExist:
            return Response(
                status=404,
                data='Not Found'
            )
        full_url = link_instance.full_url
        return HttpResponsePermanentRedirect(full_url) 
Example #29
Source File: decorators.py    From django-userena-ce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def secure_required(view_func):
    """
    Decorator to switch an url from http to https.

    If a view is accessed through http and this decorator is applied to that
    view, than it will return a permanent redirect to the secure (https)
    version of the same view.

    The decorator also must check that ``USERENA_USE_HTTPS`` is enabled. If
    disabled, it should not redirect to https because the project doesn't
    support it.

    """

    def _wrapped_view(request, *args, **kwargs):
        if not request.is_secure():
            if getattr(
                settings,
                "USERENA_USE_HTTPS",
                userena_settings.DEFAULT_USERENA_USE_HTTPS,
            ):
                request_url = request.build_absolute_uri(request.get_full_path())
                secure_url = request_url.replace("http://", "https://")
                return HttpResponsePermanentRedirect(secure_url)
        return view_func(request, *args, **kwargs)

    return wraps(view_func, assigned=WRAPPER_ASSIGNMENTS)(_wrapped_view) 
Example #30
Source File: urls.py    From simonwillisonblog with Apache License 2.0 5 votes vote down vote up
def static_redirect(request):
    return HttpResponsePermanentRedirect(
        "http://static.simonwillison.net%s" % request.get_full_path()
    )