当前位置: 首页>>代码示例>>Python>>正文


Python serializers.ValidationError方法代码示例

本文整理汇总了Python中rest_framework.serializers.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.ValidationError方法的具体用法?Python serializers.ValidationError怎么用?Python serializers.ValidationError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rest_framework.serializers的用法示例。


在下文中一共展示了serializers.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: to_jexl

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def to_jexl(self):
        comparison = self.initial_data["comparison"]
        value = self.initial_data["value"]

        if comparison == "equal":
            operator = "=="
        elif comparison == "not_equal":
            operator = "!="
        elif comparison == "greater_than":
            operator = ">"
        elif comparison == "greater_than_equal":
            operator = ">="
        elif comparison == "less_than":
            operator = "<"
        elif comparison == "less_than_equal":
            operator = "<="
        else:
            raise serializers.ValidationError(f"Unrecognized comparison {comparison!r}")

        return f"{self.left_of_operator} {operator} {value}" 
开发者ID:mozilla,项目名称:normandy,代码行数:22,代码来源:filters.py

示例2: test_validation_with_invalid_action

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def test_validation_with_invalid_action(self):
        serializer = RecipeSerializer(
            data={"action_id": "action-that-doesnt-exist", "arguments": {}}
        )

        with pytest.raises(serializers.ValidationError):
            serializer.is_valid(raise_exception=True)

        assert serializer.errors["action_id"] == [
            serializers.PrimaryKeyRelatedField.default_error_messages["incorrect_type"].format(
                data_type="str"
            )
        ]

    # If the action specified cannot be found, raise validation
    # error indicating the arguments schema could not be loaded 
开发者ID:mozilla,项目名称:normandy,代码行数:18,代码来源:test_serializers.py

示例3: test_unique_experiment_slug_update_collision

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def test_unique_experiment_slug_update_collision(self):
            action = ActionFactory(name="preference-experiment")
            arguments_a = PreferenceExperimentArgumentsFactory(
                slug="a", branches=[{"slug": "one"}]
            )
            arguments_b = PreferenceExperimentArgumentsFactory(
                slug="b", branches=[{"slug": "two"}]
            )
            # Does not throw when saving revisions
            RecipeFactory(action=action, arguments=arguments_a)
            recipe = RecipeFactory(action=action, arguments=arguments_b)

            with pytest.raises(serializers.ValidationError) as exc_info1:
                recipe.revise(arguments=arguments_a)
            error = action.errors["duplicate_experiment_slug"]
            assert exc_info1.value.detail == {"arguments": {"slug": error}} 
开发者ID:mozilla,项目名称:normandy,代码行数:18,代码来源:test_models.py

示例4: test_no_duplicates

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def test_no_duplicates(self):
            action = ActionFactory(name="preference-rollout")
            arguments_a = {"slug": "a", "preferences": [{"preferenceName": "a", "value": "a"}]}
            arguments_b = {"slug": "b", "preferences": [{"preferenceName": "b", "value": "b"}]}
            RecipeFactory(action=action, arguments=arguments_a)
            recipe_b = RecipeFactory(action=action, arguments=arguments_b)
            expected_error = action.errors["duplicate_rollout_slug"]

            # Creating a new recipe fails
            with pytest.raises(serializers.ValidationError) as exc_info1:
                RecipeFactory(action=action, arguments=arguments_a)
            assert exc_info1.value.detail == {"arguments": {"slug": expected_error}}

            # Revising an existing recipe fails
            with pytest.raises(serializers.ValidationError) as exc_info2:
                recipe_b.revise(arguments=arguments_a)
            assert exc_info2.value.detail == {"arguments": {"slug": expected_error}} 
开发者ID:mozilla,项目名称:normandy,代码行数:19,代码来源:test_models.py

示例5: validate

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def validate(self, attrs):
        attrs = super().validate(attrs)
        phone_number = attrs.get("phone_number", None)
        security_code, session_token = (
            attrs.get("security_code", None),
            attrs.get("session_token", None),
        )
        backend = get_sms_backend(phone_number=phone_number)
        verification, token_validatation = backend.validate_security_code(
            security_code=security_code,
            phone_number=phone_number,
            session_token=session_token,
        )

        if verification is None:
            raise serializers.ValidationError(_("Security code is not valid"))
        elif token_validatation == backend.SESSION_TOKEN_INVALID:
            raise serializers.ValidationError(_("Session Token mis-match"))
        elif token_validatation == backend.SECURITY_CODE_EXPIRED:
            raise serializers.ValidationError(_("Security code has expired"))
        elif token_validatation == backend.SECURITY_CODE_VERIFIED:
            raise serializers.ValidationError(_("Security code is already verified"))

        return attrs 
开发者ID:CuriousLearner,项目名称:django-phone-verify,代码行数:26,代码来源:serializers.py

示例6: post

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def post(self, request, username=None):
        follower = self.request.user.profile

        try:
            followee = Profile.objects.get(user__username=username)
        except Profile.DoesNotExist:
            raise NotFound('A profile with this username was not found.')

        if follower.pk is followee.pk:
            raise serializers.ValidationError('You can not follow yourself.')

        follower.follow(followee)

        serializer = self.serializer_class(followee, context={
            'request': request
        })

        return Response(serializer.data, status=status.HTTP_201_CREATED) 
开发者ID:tryolabs,项目名称:aws-workshop,代码行数:20,代码来源:views.py

示例7: validate

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def validate(self, data):
        """Validate.

        Verify that the person who offers the ride is member
        and also the same user making the request.
        """
        if self.context['request'].user != data['offered_by']:
            raise serializers.ValidationError('Rides offered on behalf of others are not allowed.')

        user = data['offered_by']
        circle = self.context['circle']
        try:
            membership = Membership.objects.get(
                user=user,
                circle=circle,
                is_active=True
            )
        except Membership.DoesNotExist:
            raise serializers.ValidationError('User is not an active member of the circle.')

        if data['arrival_date'] <= data['departure_date']:
            raise serializers.ValidationError('Departure date must happen after arrival date.')

        self.context['membership'] = membership
        return data 
开发者ID:pablotrinidad,项目名称:cride-platzi,代码行数:27,代码来源:rides.py

示例8: validate_passenger

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def validate_passenger(self, data):
        """Verify passenger exists and is a circle member."""
        try:
            user = User.objects.get(pk=data)
        except User.DoesNotExist:
            raise serializers.ValidationError('Invalid passenger.')

        circle = self.context['circle']
        try:
            membership = Membership.objects.get(
                user=user,
                circle=circle,
                is_active=True
            )
        except Membership.DoesNotExist:
            raise serializers.ValidationError('User is not an active member of the circle.')

        self.context['user'] = user
        self.context['member'] = membership
        return data 
开发者ID:pablotrinidad,项目名称:cride-platzi,代码行数:22,代码来源:rides.py

示例9: _get_providers

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def _get_providers(self, provider):
        """Get the providers.

        Return the appropriate provider and provider resource type from self.provider_resource_list

        """

        access = []
        provider_list = provider.split("_")
        if "all" in provider_list:
            for p, v in self.provider_resource_list.items():
                access.extend(v)
        else:
            for p in provider_list:
                if self.provider_resource_list.get(p) is None:
                    msg = f'Invalid provider "{p}".'
                    raise ValidationError({"details": _(msg)})
                access.extend(self.provider_resource_list[p])
        return access 
开发者ID:project-koku,项目名称:koku,代码行数:21,代码来源:query_params.py

示例10: get_tenant

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def get_tenant(user):
    """Get the tenant for the given user.

    Args:
        user    (DjangoUser): user to get the associated tenant
    Returns:
        (Tenant): Object used to get tenant specific data tables
    Raises:
        (ValidationError): If no tenant could be found for the user

    """
    tenant = None
    if user:
        try:
            customer = user.customer
            tenant = Tenant.objects.get(schema_name=customer.schema_name)
        except User.DoesNotExist:
            pass
    if tenant:
        return tenant
    raise ValidationError({"details": _("Invalid user definition")}) 
开发者ID:project-koku,项目名称:koku,代码行数:23,代码来源:query_params.py

示例11: get_customer_from_context

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def get_customer_from_context(self):
        """Get customer from context."""
        customer = self.context.get("customer")
        if customer:
            return customer
        else:
            request = self.context.get("request")
            if request and hasattr(request, "META"):
                _, json_rh_auth = extract_header(request, RH_IDENTITY_HEADER)
                if (
                    json_rh_auth
                    and "identity" in json_rh_auth
                    and "account_number" in json_rh_auth["identity"]  # noqa: W504
                ):
                    account = json_rh_auth["identity"]["account_number"]
                if account:
                    schema_name = create_schema_name(account)
                    customer = Customer.objects.get(schema_name=schema_name)
                else:
                    key = "customer"
                    message = "Customer for requesting user could not be found."
                    raise serializers.ValidationError(error_obj(key, message))
        return customer 
开发者ID:project-koku,项目名称:koku,代码行数:25,代码来源:serializers.py

示例12: test_get_providers_with_nonsense_provider

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def test_get_providers_with_nonsense_provider(self):
        """Test get providers raises validation error with nonsense provider."""
        fake_request = Mock(
            spec=HttpRequest,
            user=Mock(access=Mock(get=lambda key, default: default), customer=Mock(schema_name="acct10001")),
            GET=Mock(urlencode=Mock(return_value="")),
        )
        fake_view = Mock(
            spec=ReportView,
            provider=self.FAKE.word(),
            query_handler=Mock(provider=random.choice(PROVIDERS)),
            report=self.FAKE.word(),
            serializer=Mock,
            tag_handler=[],
        )
        params = QueryParameters(fake_request, fake_view)
        with self.assertRaises(ValidationError):
            params._get_providers("nonsense") 
开发者ID:project-koku,项目名称:koku,代码行数:20,代码来源:tests_query_params.py

示例13: is_valid

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def is_valid(self, *args, **kwargs):
        valid = super(PolymorphicSerializer, self).is_valid(*args, **kwargs)
        try:
            resource_type = self._get_resource_type_from_mapping(self.validated_data)
            serializer = self._get_serializer_from_resource_type(resource_type)
        except serializers.ValidationError:
            child_valid = False
        else:
            child_valid = serializer.is_valid(*args, **kwargs)
            self._errors.update(serializer.errors)
        return valid and child_valid 
开发者ID:apirobot,项目名称:django-rest-polymorphic,代码行数:13,代码来源:serializers.py

示例14: _get_resource_type_from_mapping

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def _get_resource_type_from_mapping(self, mapping):
        try:
            return mapping[self.resource_type_field_name]
        except KeyError:
            raise serializers.ValidationError({
                self.resource_type_field_name: 'This field is required',
            }) 
开发者ID:apirobot,项目名称:django-rest-polymorphic,代码行数:9,代码来源:serializers.py

示例15: _get_serializer_from_resource_type

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ValidationError [as 别名]
def _get_serializer_from_resource_type(self, resource_type):
        try:
            model = self.resource_type_model_mapping[resource_type]
        except KeyError:
            raise serializers.ValidationError({
                self.resource_type_field_name: 'Invalid {0}'.format(
                    self.resource_type_field_name
                )
            })

        return self._get_serializer_from_model_or_instance(model) 
开发者ID:apirobot,项目名称:django-rest-polymorphic,代码行数:13,代码来源:serializers.py


注:本文中的rest_framework.serializers.ValidationError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。