python类ValidationError()的实例源码

auth.py 文件源码 项目:momo-wps 作者: WPS-team-4 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get(self, request, *args, **kwargs):
        try:
            key = request.query_params['key']
            user = MomoUser.objects.get(hash_username=key)
            user.is_active = True
            user.save()
        except MomoUser.DoesNotExist:
            raise Http404
        except MultipleObjectsReturned:
            raise ValidationError(detail="?? ?? url? ?? ?????.")
        except MultiValueDictKeyError:
            raise ValidationError(detail="?? ?? url? ?? ?????.")

        return Response({"user_pk": user.pk,
                         "detail": "user? ????????.",
                         "url": reverse('index', request=request)}, status=status.HTTP_200_OK,
                        template_name='member/activate.html')
post.py 文件源码 项目:momo-wps 作者: WPS-team-4 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def create(self, request, *args, **kwargs):
        data = request.data

        photo = data.get('photo')
        description = data.get('description')

        if photo or description:
            if photo:
                file = request.FILES['photo']
                data['photo'] = file
            else:
                pass
            serializer = PostSerializer(data=data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)

            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        else:
            raise ValidationError(detail="photo? description ? ??? ?? ? ??????.")
views.py 文件源码 项目:experiments-viewer 作者: mozilla 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def verify_google_token(request):
    token = request.data.get('token')
    if token is None:
        raise ValidationError({'detail': 'Auth token required.'})
    try:
        idinfo = client.verify_id_token(token, settings.GOOGLE_AUTH_KEY)
        if idinfo['iss'] not in ['accounts.google.com',
                                 'https://accounts.google.com']:
            raise crypt.AppIdentityError('Wrong issuer.')
        if idinfo.get('hd') != settings.GOOGLE_AUTH_HOSTED_DOMAIN:
            raise crypt.AppIdentityError('Wrong hosted domain.')
    except crypt.AppIdentityError as e:
        raise AuthenticationFailed(e)
    defaults = {
        'email': idinfo['email'],
        'first_name': idinfo.get('given_name', ''),
        'last_name': idinfo.get('family_name', ''),
    }
    user, created = get_user_model().objects.get_or_create(
        username=idinfo['email'], defaults=defaults)
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)
    return Response({})
rest_framework_swagger_views.py 文件源码 项目:drf-swagger-missing 作者: tovmeod 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get(self, request):
        generator = BetterSchemaGenerator(
            title=self.title,
            url=self.url,
            description=self.description,
            patterns=self.patterns,
            urlconf=self.urlconf,
            definitions=self.definitions,
            version=self.version,
            check_view_permissions=self.check_view_permissions
        )
        schema = generator.get_schema(request=request)

        if not schema:
            raise exceptions.ValidationError(
                'The schema generator did not return a schema Document'
            )

        return Response(schema)
serializers.py 文件源码 项目:aa-stripe 作者: ArabellaTech 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def create(self, validated_data):
        instance = None
        if validated_data.get("stripe_js_response"):
            # Create a Customer
            try:
                user = self.context['request'].user
                stripe_js_response = validated_data.pop("stripe_js_response")
                instance = StripeCustomer.objects.create(
                    user=user, stripe_js_response=stripe_js_response)
                instance.create_at_stripe()
            except stripe.StripeError as e:
                logging.error(
                    "[AA-Stripe] creating customer failed for user {user.id}: {error}".format(user=user, error=e)
                )
                raise ValidationError({"stripe_error": e._message})

        return instance
views.py 文件源码 项目:apis-against-huge-manatees 作者: rgegriff 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def post(self, request, join_id):
        try:
            game = Game.objects.get(join_id=join_id)
        except Game.DoesNotExist:
            raise NotFound("Invalid join_id",404)

        if game.game_state != 'starting':
            raise ValidationError("You can no longer join this game")

        data = request.data
        enforce_required_params(['name'],data)
        player = Player.objects.create(name=data['name'], game=game)
        if game.num_players == game.players.count():
            game.game_state = 'pick_wc'
            game.save()
            game.start_new_round()

        return Response({
            'player':player.get_dict(show_private=True),
            'game':game.get_dict()})
views.py 文件源码 项目:apis-against-huge-manatees 作者: rgegriff 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def post(self, request, join_id):
        data = request.data
        enforce_required_params(['cards[]'], data)
        player = request.user.player
        cards = data.getlist('cards[]')
        game = request.user.player.game
        if game.game_state != "pick_wc":
            raise ValidationError({'error':"Unable to play cards at this moment"},400)
        if game.current_black_card.pick != len(cards):
            raise ValidationError({'error':"incorrect number of decks", 'value':cards},400)
        playcards = map(lambda card:PlayCard(player=player, card_id=card), cards)
        PlayCard.objects.bulk_create(playcards)
        if game.players_played_count() == game.num_players - 1: #  if everyone except the cardczar has played, state change
            game.game_state = "pick_win"
            game.save()
        return Response({'status':"success"})


# pick winner
fork.py 文件源码 项目:jatumba-backend 作者: YetAnotherTeam 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def validate(self, attrs):
        request = self.context['request']
        user = request.user
        band = attrs['band']

        if not band.members.filter(user=user).exists():
            raise ValidationError('?? ?? ???????? ? ???? ??????.')

        source_composition_version = attrs['source_composition_version']

        if source_composition_version.composition.band_id == band.id:
            raise ValidationError(
                '?????? ???????? ?????????? ? ??????, ??????? ??? ?????????? ? ??? ???????????.'
            )

        return attrs
web_socket.py 文件源码 项目:jatumba-backend 作者: YetAnotherTeam 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def commit(self, request, data, *args, **kwargs):
        user_id = request.channel_session.get('user')
        if user_id is not None:
            composition_id = kwargs.get('composition_id')
            data['composition'] = composition_id
            if (DiffCompositionVersion.objects
                    .filter(composition_id=composition_id)
                    .count() <= 1):
                raise ValidationError('Nothing to commit.')
            diff_version = (DiffCompositionVersion.objects
                            .filter(composition_id=composition_id)
                            .last())
            composition_version = self.perform_commit(diff_version, user_id)
            self.route_send(
                Group(self.COMPOSITION_GROUP_TEMPLATE % composition_id),
                CompositionVersionSerializer(composition_version).data,
                status.HTTP_201_CREATED
            )
        else:
            raise PermissionDenied
test_serializers.py 文件源码 项目:django-rest-witchcraft 作者: shosca 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def test_composite_serializer_can_handle_errors_during_update(self):

        class EngineSerializer(CompositeSerializer):

            class Meta:
                composite = Vehicle.engine

            def set_cylinders(self, instance, field, value):
                assert False, 'Some error'

        data = {
            'cylinders': 2,
        }
        engine = Engine(4, 2345, 'apple', 'petrol')

        serializer = EngineSerializer(engine, data=data, partial=True)
        self.assertTrue(serializer.is_valid(), serializer.errors)

        with self.assertRaises(ValidationError):
            serializer.save()
test_serializers.py 文件源码 项目:django-rest-witchcraft 作者: shosca 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_patch_update_to_list_with_new_list_with_nested_raises_for_a_bad_pk(self):
        vehicle = Vehicle(
            name='Test vehicle', type=VehicleType.bus, engine=Engine(4, 1234, None,
                                                                     None), owner=session.query(Owner).get(1),
            other=VehicleOther(advertising_cost=4321), options=session.query(Option).filter(Option.id.in_([1, 2])).all()
        )

        class VehicleSerializer(ModelSerializer):

            class Meta:
                model = Vehicle
                session = session
                fields = ('options', )
                extra_kwargs = {'options': {'allow_null': False}}

        data = {'options': [{'id': 1, 'name': 'Test 1'}, {'id': 5, 'name': 'Test 5'}]}

        serializer = VehicleSerializer(instance=vehicle, data=data, partial=True)

        self.assertTrue(serializer.is_valid(), serializer.errors)

        with self.assertRaises(ValidationError):
            serializer.update(vehicle, serializer.validated_data)
test_serializers.py 文件源码 项目:django-rest-witchcraft 作者: shosca 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_update_generates_validation_error_when_required_many_to_one_instance_not_found(self):
        vehicle = Vehicle(
            name='Test vehicle', type=VehicleType.bus, engine=Engine(4, 1234, None,
                                                                     None), owner=session.query(Owner).get(1),
            other=VehicleOther(advertising_cost=4321), options=session.query(Option).filter(Option.id.in_([1, 2])).all()
        )

        class VehicleSerializer(ModelSerializer):

            class Meta:
                model = Vehicle
                session = session
                fields = ('owner', )
                extra_kwargs = {'owner': {'allow_null': False}}

        data = {'owner': {'id': 1234}}

        serializer = VehicleSerializer(instance=vehicle, data=data, partial=True)
        self.assertTrue(serializer.is_valid(), serializer.errors)

        with self.assertRaises(ValidationError):
            serializer.update(vehicle, serializer.validated_data)
serializers.py 文件源码 项目:django-rest-witchcraft 作者: shosca 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_object(self, validated_data, instance=None):
        """
        Returns model object instance using the primary key values in the `validated_data`.
        If the instance is not found, depending on serializer's `allow_create` value, it will create a new model
        instance or raise an error.
        """
        pks = self.get_primary_keys(validated_data)
        checked_instance = None
        if pks:
            checked_instance = self.session.query(self.model).get(pks)
        else:
            checked_instance = instance

        if checked_instance is not None:
            return checked_instance

        if self.allow_create:
            return self.model()

        if self.allow_null:
            return checked_instance

        raise ValidationError('No instance of `{}` found with primary keys `{}`'.format(self.model.__name__, pks))
create_person.py 文件源码 项目:occasions-server 作者: travisbloom 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def create(self, validated_data):
        locations = validated_data.pop('locations')
        relationship_type = validated_data.pop('relationship_type')
        person = Person(**validated_data)
        person.save()
        if not locations:
            raise ValidationError('People must have at least one address.')
        for location in locations:
            location = Location(**location)
            location.save()
            associated_location = AssociatedLocation(
                location=location, person=person)
            associated_location.save()
        relationship = Relationship(
            relationship_type=relationship_type,
            from_person=self.context['user'].person,
            to_person=person
        )
        relationship.save()
        return person
serializers.py 文件源码 项目:occasions-server 作者: travisbloom 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def create(self, validated_data):
        new_event = validated_data.pop('event', None)
        existing_event = validated_data.pop('event_id', None)
        if not existing_event:
            if not new_event:
                raise ValidationError({
                    'event': 'You must have a new event or event_id attached to this associated event.'
                })
            else:
                existing_event = EventSerializer().create(new_event)
        associated_event = AssociatedEvent(
            event=existing_event,
            receiving_person=validated_data.get('receiving_person_id'),
            creating_person=self.context['user'].person
        )
        associated_event.save()
        return associated_event
serializers.py 文件源码 项目:rptp 作者: potykion 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def validate(self, data):
        """
        Format VK video to rptp video format.

        Args:
            data: VK video dict.

        Returns:
            Dict used to create Video object.

        """
        try:
            return {
                'title': data['title'],
                'preview': data['photo_320'],
                'url': f"https://m.vk.com/video{data['owner_id']}_{data['id']}",
                'duration': data['duration'],
                'views': data['views']
            }
        except KeyError:
            raise ValidationError({'video': 'Video format is invalid.'})


问题


面经


文章

微信
公众号

扫码关注公众号