本文整理匯總了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}"
示例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
示例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}}
示例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}}
示例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
示例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)
示例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
示例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
示例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
示例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")})
示例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
示例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")
示例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
示例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',
})
示例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)