Python django.http.response 模块,Http404() 实例源码

我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用django.http.response.Http404()

项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def webfinger_view(request):
    """Generate a webfinger document."""
    q = request.GET.get("q")
    if not q:
        raise Http404()
    username = q.split("@")[0]
    if username.startswith("acct:"):
        username = username.replace("acct:", "", 1)
    user = get_object_or_404(User, username=username)
    # Create webfinger document
    webfinger = generate_legacy_webfinger(
        "diaspora",
        handle="{username}@{domain}".format(username=user.username, domain=settings.SOCIALHOME_DOMAIN),
        host=settings.SOCIALHOME_URL,
        guid=str(user.profile.guid),
        public_key=user.profile.rsa_public_key
    )
    return HttpResponse(webfinger, content_type="application/xrd+xml")
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def hcard_view(request, guid):
    """Generate a hcard document.

    For local users only.
    """
    try:
        profile = get_object_or_404(Profile, guid=guid, user__isnull=False)
    except ValueError:
        raise Http404()
    hcard = generate_hcard(
        "diaspora",
        hostname=settings.SOCIALHOME_URL,
        fullname=profile.name,
        firstname=profile.get_first_name(),
        lastname=profile.get_last_name(),
        photo300=profile.safer_image_url_large,
        photo100=profile.safer_image_url_medium,
        photo50=profile.safer_image_url_small,
        searchable="true" if profile.public else "false",
        guid=profile.guid,
        username=profile.user.username,
        public_key=profile.rsa_public_key,
    )
    return HttpResponse(hcard)
项目:vaultier    作者:Movile    | 项目源码 | 文件源码
def initial(self, request, *args, **kwargs):
        """
        Find parent if any
        """
        node_id = self.request.QUERY_PARAMS.get('node')
        parent_id = self.request.QUERY_PARAMS.get('parent_node')
        if node_id and node_id.isdigit():
            try:
                node = Node.objects.get(id=node_id)
            except Node.DoesNotExist:
                raise Http404("Parent node was not found.")
            else:
                self.kwargs['node'] = node
        elif parent_id and parent_id.isdigit():
            try:
                node = Node.objects.get(id=parent_id)
            except Node.DoesNotExist:
                raise Http404("Parent node was not found.")
            else:
                self.kwargs['parent_node'] = node

        else:
            detail = "node or node_parent query parameter is missing"
            raise CustomAPIException(status_code=400, detail=detail)
        return super(PolicyViewSet, self).initial(request, *args, **kwargs)
项目:djreservation    作者:luisza    | 项目源码 | 文件源码
def finish_reservation(request):
    if not hasattr(request, 'reservation'):
        raise Http404(_("No reservation object started"))

    if request.method == "GET":
        response = render(
            request,
            'djreservation/reservation_confirm.html',
            {"reservation": request.reservation})
    elif request.method == "POST":
        reservation = request.reservation
        reservation.status = reservation.REQUESTED
        reservation.save()
        request.reservation = None
        send_reservation_email(reservation, request.user)
        response = render(
            request, 'djreservation/reservation_finished.html')
        response.set_cookie("reservation", "0")
        messages.success(request, _('Reservation finised'))
    return response
项目:djreservation    作者:luisza    | 项目源码 | 文件源码
def update_reservation_by_token(request, pk, token, status):
    token_reservation = get_object_or_404(ReservationToken, reservation=pk,
                                          token=token)
    status_available = list(dict(Reservation.STATUS).keys())
    if int(status) not in status_available:
        raise Http404()

    reservation = token_reservation.reservation

    if int(status) == Reservation.ACCEPTED:
        reservation.product_set.all().update(borrowed=True)
    reservation.status = status
    reservation.save()
    token_reservation.delete()
    messages.success(request, _('Reservation updated successful'))
    return redirect("/")
项目:foundation    作者:altio    | 项目源码 | 文件源码
def get_object(self, queryset=None):
        """
        Returns the object the view is displaying.

        By default this requires `self.queryset` and a `pk` or `slug` argument
        in the URLconf, but subclasses can override this to return any object.
        """

        obj = super(SingleObjectMixin, self).get_object(queryset=queryset)

        # TODO: Consider if we want to support normal pk/slug stuff...

        if not obj:
            raise Http404(_("No %(verbose_name)s found matching the query") %
                          {'verbose_name': self.model._meta.verbose_name})
        return obj
项目:django-mongo-rest    作者:TrueSkills    | 项目源码 | 文件源码
def endpoint(self, request, *args, **kwargs):
        try:
            return super(PageView, self).endpoint(request, *args, **kwargs)
        except ApiException as e:
            if e.error_code == ERROR_CODES.PARAMS:
                if self.signature_salt:
                    return redirect('/error/invalid_signature/')
                raise Http404()

            if e.error_code == ERROR_CODES.SIGNATURE:
                return redirect('/error/invalid_signature/')

            if e.error_code == ERROR_CODES.EXPIRED_SIGNATURE:
                return redirect('/error/expired_link/')

            if e.status_code != 404:
                return HttpResponse(e.message, status=e.status_code)

            if e.error_code != ERROR_CODES.PERMISSION:
                raise Http404()

            path = request.get_full_path()
            return redirect_to_login(path, settings.LOGIN_URL, 'next')
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def content_fetch_view(request, objtype, guid):
    """Diaspora content fetch view.

    Returns the signed payload for the public content. Non-public content will return 404.

    If the content is not local, redirect to content author server.

    Args:
        objtype (str) - Diaspora content type. Currently if it is `status_message`, `post` or `reshare`,
            we try to find `Content`.
        guid (str) - The object guid to look for.
    """
    if objtype not in ["status_message", "post", "reshare", "comment"]:
        raise Http404()
    content = get_object_or_404(Content, guid=guid, visibility=Visibility.PUBLIC)
    if not content.local:
        url = "https://%s/fetch/%s/%s" % (
            content.author.handle.split("@")[1], objtype, guid
        )
        return HttpResponseRedirect(url)
    entity = make_federable_content(content)
    message = get_full_xml_representation(entity, content.author.private_key)
    document = MagicEnvelope(
        message=message, private_key=content.author.private_key, author_handle=content.author.handle
    )
    return HttpResponse(document.render(), content_type="application/magic-envelope+xml")
项目:django-datawatch    作者:RegioHelden    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        try:
            return super(ResultView, self).get(request, *args, **kwargs)
        except Http404:
            messages.add_message(self.request, messages.WARNING,
                                 _('Check result does not exist (anymore)'))
            return HttpResponseRedirect(redirect_to=reverse_lazy(
                'django_datawatch_index'))
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_not_live(self):
        """
        Purchasable course runs must be live
        """
        course_run, user = create_purchasable_course_run()
        program = course_run.course.program
        program.live = False
        program.save()

        with self.assertRaises(Http404):
            get_purchasable_course_run(course_run.edx_course_key, user)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_financial_aid_not_available(self):
        """
        Purchasable course runs must have financial aid available
        """
        course_run, user = create_purchasable_course_run()
        program = course_run.course.program
        program.financial_aid_availability = False
        program.save()

        with self.assertRaises(Http404):
            get_purchasable_course_run(course_run.edx_course_key, user)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_no_program_enrollment(self):
        """
        For a user to purchase a course run they must already be enrolled in the program
        """
        course_run, user = create_purchasable_course_run()
        ProgramEnrollment.objects.filter(program=course_run.course.program, user=user).delete()
        with self.assertRaises(Http404):
            create_unfulfilled_order(course_run.edx_course_key, user)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_no_program_enrollment(self):
        """
        If a user is not enrolled a 404 should be raised when getting the price
        """
        course_run, user = create_purchasable_course_run()
        ProgramEnrollment.objects.filter(program=course_run.course.program, user=user).delete()
        with self.assertRaises(Http404):
            calculate_run_price(course_run, user)
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should raise 404 if there's no PublicationSeries with that slug."
        with self.assertRaises(Http404):
            response = views.PublicationSeriesDetailView.as_view()(
                                                        self.request, slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_non_numeric_page(self):
        "PaginatedListView should raise 404 if we ask for a non-numeric page that isn't 'last'."
        request = self.factory.get('/fake-path/?p=asdf')
        with self.assertRaises(Http404):
            response = views.PublicationListView.as_view()(request)
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_invalid_page(self):
        "PaginatedListView should raise 404 if we ask for a page number that doesn't exist."
        # Use a URL with p=99:
        request = self.factory.get('/fake-path/?p=99')
        with self.assertRaises(Http404):
            response = views.PublicationListView.as_view()(request)
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should raise 404 if there's no Publication with that slug."
        with self.assertRaises(Http404):
            response = views.PublicationDetailView.as_view()(self.request, slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should raise 404 if it's a date before our first year."
        with self.assertRaises(Http404):
            response = views.ReadingYearArchiveView.as_view()(
                                                    self.request, year='2016')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should respond with 404 with an invalid kind_slug."
        with self.assertRaises(Http404):
            response = views.EventListView.as_view()(
                                            self.request, kind_slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404_kind_slug(self):
        "It should raise 404 if there's no Event with that kind_slug."
        with self.assertRaises(Http404):
            response = views.EventDetailView.as_view()(
                                        self.request, kind_slug='nope', slug='my-gig')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404_pk(self):
        "It should raise 404 if there's no Event with that slug."
        with self.assertRaises(Http404):
            response = views.EventDetailView.as_view()(
                                        self.request, kind_slug='gigs', slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should raise 404 if there's no Movie with that slug."
        with self.assertRaises(Http404):
            response = views.EventDetailView.as_view()(
                                    self.request, kind_slug='movies', slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should raise 404 if there's no Play with that slug."
        with self.assertRaises(Http404):
            response = views.EventDetailView.as_view()(
                                    self.request, kind_slug='plays', slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should respond with 404."
        with self.assertRaises(Http404):
            response = views.ClassicalWorkDetailView.as_view()(
                                                        self.request, slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should respond with 404."
        with self.assertRaises(Http404):
            response = views.DancePieceDetailView.as_view()(self.request, slug='nope')
项目:django-spectator    作者:philgyford    | 项目源码 | 文件源码
def test_response_404(self):
        "It should raise 404 if there's no Venue with that slug."
        with self.assertRaises(Http404):
            response = views.VenueDetailView.as_view()(self.request, slug='nope')
项目:django-rest-framework-client    作者:qvantel    | 项目源码 | 文件源码
def get_object_or_404(klass, *args, **kwargs):
    """
    Similar to django.shortcuts.get_object_or_404 but it also supports klass argument to be of type
    restframework.Model or PartiallyFiltered
    """
    if isinstance(klass, (ModelBase, PartiallyFiltered)):
        partially_filtered = klass if isinstance(klass, PartiallyFiltered) else klass.objects.all()
        model = partially_filtered.model
        try:
            return partially_filtered.get(*args, **kwargs)
        except model.DoesNotExist:
            raise Http404('No %s matches the given query.' % model._meta.object_name)
    else:
        return django_get_object_or_404(klass, *args, **kwargs)
项目:django-rest-framework-client    作者:qvantel    | 项目源码 | 文件源码
def test_get_object_or_404_raises_404_on_DoesNotExist(self, rest_call_mock):
        rest_call_mock.side_effect = Customer.DoesNotExist
        with self.assertRaises(Http404):
            restframeworkclient.get_object_or_404(Customer, param='value')
项目:Intranet    作者:mituSkillologies-Interns    | 项目源码 | 文件源码
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    # try:
    #     question = Question.objects.get(pk=question_id)
    # except Question.DoesNotExist:
    #     raise Http404("Question does not exists.")
    return render(request, 'polls/detail.html',{'question':question})
    #return HttpResponse("You're looking at question %s." % question_id)
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
def post(self, request):
        try:
            code = request.data['code']
        except KeyError:
            return redirect('/500')

        callback_uri = request.build_absolute_uri(reverse('fitbit-complete'))
        fb = utils.create_fitbit(callback_uri=callback_uri)

        try:
            token = fb.client.fetch_access_token(code, callback_uri)
            access_token = token['access_token']
            fitbit_user_id = token['user_id']
        except KeyError:
            raise Http404('Invalid Token')

        user = request.user
        UserFitbit.objects.update_or_create(user=user, defaults={
            'fitbit_user_id': fitbit_user_id,
            'access_token': access_token,
            'refresh_token': token['refresh_token'],
            'expires_at': token['expires_at'],
        })

        next_url = request.session.pop('fitbit_next', None) or utils.get_setting('FITBIT_LOGIN_REDIRECT')

        response = {'next_url': next_url}
        return Response(response)
项目:vaultier    作者:Movile    | 项目源码 | 文件源码
def initial(self, request, *args, **kwargs):
        """
        Find parent if any
        """
        parent_id = self.request.QUERY_PARAMS.get('parent')
        if parent_id and parent_id.isdigit():
            try:
                node = Node.objects.get(id=parent_id)
            except Node.DoesNotExist:
                raise Http404("Parent node was not found.")
            else:
                self.kwargs['parent'] = node
        return super(NodeViewSet, self).initial(request, *args, **kwargs)
项目:website    作者:pyslackers    | 项目源码 | 文件源码
def test_missing_post(self, rf):
        with pytest.raises(Http404):
            request = rf.get('/blog/foo-bar/')
            PostDetailView.as_view()(request, slug='foo-bar')
项目:Shanbay_Clone    作者:cheng10    | 项目源码 | 文件源码
def word_detail(request, word_name):
    try:
        word = Word.objects.get(text=word_name)
    except Word.DoesNotExist:
        raise Http404()
    return render(request, 'word.html', {'word': word})
项目:C3FOCSite    作者:Technikradio    | 项目源码 | 文件源码
def render_image_detail(request, medium_id):
    image = Media.objects.get(pk=int(medium_id))
    if image is None:
        raise Http404("No media found")
    a = "<h2>" + image.headline + "</h2><center>"
    a += render_image(image)
    a += "</center><article>" + image.cachedText + "</article>"
    return a
项目:finem_imperii    作者:jardiacaj    | 项目源码 | 文件源码
def leave_view(request, organization_id):
    organization = get_object_or_404(Organization, id=organization_id)

    if request.hero not in organization.character_members.all():
        raise Http404("Hero is not a member")

    organization.remove_member(request.hero)

    messages.success(request, "You left {}".format(organization), "success")
    return redirect(organization.get_absolute_url())
项目:finem_imperii    作者:jardiacaj    | 项目源码 | 文件源码
def battlefield_view_iframe(request, battle_id):
    battle = get_object_or_404(Battle, pk=battle_id)

    if not battle.started:
        raise Http404()

    context = {
        'battle_data': json.dumps(render_battle_for_view(battle))
    }
    return render(request, 'battle/battlefield_view_iframe.html', context=context)
项目:django-mongo-rest    作者:TrueSkills    | 项目源码 | 文件源码
def __call__(self, request, i):
        doc = self.model_cls.find_by_id(i, params=FindParams(request=request))
        if not doc:
            raise Http404(self.model_cls.msg404(obj_id=i))
        return doc
项目:django-mongo-rest    作者:TrueSkills    | 项目源码 | 文件源码
def page_not_found(_):
    raise Http404()
项目:django-mongo-rest    作者:TrueSkills    | 项目源码 | 文件源码
def endpoint(self, request, *args, **kwargs):
        if not self.is_authorized(request):
            raise ApiException('Not found', 404, error_code=ERROR_CODES.PERMISSION)

        if not _enforce_allowed_methods(request, self.allowed_methods):
            raise ApiException('%s not supported' % request.method, 405)

        if (request.method in CONTENT_TYPE_METHODS and
                request.content_type not in to_list(self.expected_content_type or [])):
            raise ApiException('Expected Content-Type: %s' % self.expected_content_type, 400)

        _parse_params(request)

        if self.params:
            try:
                kwargs.update(get_params(request.dmr_params, self.params, request))
            except ValueError as e:
                raise ApiException(e.args[0], 400, error_code=ERROR_CODES.PARAMS)
            except Http404 as e:
                raise ApiException(e.args[0], 404)

        if self.signature_salt:
            max_age = self.link_valid_seconds or None
            try:
                verify_signature(request, expected_salt=self.signature_salt, max_age=max_age)
            except InvalidSig:
                raise ApiException('Invalid signature', 403, error_code=ERROR_CODES.SIGNATURE)
            except ExpiredSig:
                raise ApiException('Expired signature', 403, error_code=ERROR_CODES.EXPIRED_SIGNATURE)

        return self.main_wrapper(request, *args, **kwargs)
项目:django-mongo-rest    作者:TrueSkills    | 项目源码 | 文件源码
def get_params_api(dct, params, request):
    try:
        return get_params(dct, params, request)
    except ValueError as e:
        raise ApiException(e.args[0], 400)
    except Http404 as e:
        raise ApiException(e.args[0], 404)
项目:django-mongo-rest    作者:TrueSkills    | 项目源码 | 文件源码
def update(self, request, obj_id):
        if not obj_id:
            raise Http404()

        existing_model = get_orm_object_or_404_by_id(self.model, request, obj_id)
        self._refuse_conflicting_update(request.dmr_params, request, existing_model)

        try:
            obj = self.extract_request_model(request, request.dmr_params, self.editable_fields,
                                             existing=existing_model)
        except ValidationError as e:
            raise ApiException(e.to_dict(), 400)

        unset = []
        for field_name, field in self.model._fields.iteritems():
            val = request.dmr_params.get(field_name, True)
            if val is None or val == []:
                unset.append(field_name)

        update_params = UpdateParams(request=None if request.user.is_superuser else request, unset=unset)

        try:
            del obj['_id'] # Don't try to update this
            res = self.model.update_by_id(obj_id, update_params=update_params, **obj)
        except ModelPermissionException:
            raise ApiException(self.model.msg404(), 400)
        except DuplicateKeyError:
            raise ApiException('Duplicate object', 400, 'DUP')
        else:
            if isinstance(self.model.id, ObjectIdField):
                obj['_id'] = ObjectId(obj_id)
            else:
                obj['_id'] = obj_id
            self._create_audit_log(request, obj, audit.ACTIONS.UPDATE, self.editable_fields)

        if not res.matched_count:
            raise ApiException(self.model.msg404(), 404)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def get_purchasable_course_run(course_key, user):
    """
    Gets a course run, or raises Http404 if not purchasable. To be purchasable a course run
    must not already be purchased, must be part of a live program, must be part of a program
    with financial aid enabled, with a financial aid object, and must have a valid price.

    Args:
        course_key (str):
            An edX course key
        user (User):
            The purchaser of the course run
    Returns:
        CourseRun: A course run
    """
    # Make sure it's connected to a live program, it has a valid price, and the user is enrolled in the program already
    try:
        course_run = get_object_or_404(
            CourseRun,
            edx_course_key=course_key,
            course__program__live=True,
            course__program__financial_aid_availability=True,
        )
    except Http404:
        log.warning("Course run %s is not purchasable", course_key)
        raise

    if not FinancialAid.objects.filter(
            tier_program__current=True,
            tier_program__program__course__courserun=course_run,
            user=user,
            status__in=FinancialAidStatus.TERMINAL_STATUSES,
    ).exists():
        log.warning("Course run %s has no attached financial aid for user %s", course_key, get_social_username(user))
        raise ValidationError(
            "Course run {} does not have a current attached financial aid application".format(course_key)
        )

    # Make sure it's not already purchased
    if Line.objects.filter(
            order__status=Order.FULFILLED,
            order__user=user,
            course_key=course_run.edx_course_key,
    ).exists():
        mmtrack = get_mmtrack(user, course_run.course.program)
        if not has_to_pay_for_exam(mmtrack, course_run.course):
            log.warning("Course run %s is already purchased by user %s", course_key, user)
            raise ValidationError("Course run {} is already purchased".format(course_key))

    return course_run