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


Python exceptions.ValidationError方法代码示例

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


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

示例1: is_valid

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def is_valid(self, raise_exception=False):
        super().is_valid(raise_exception=raise_exception)

        if "xpi" in self.validated_data:
            try:
                Extension(**self.validated_data).populate_metadata()
            except DjangoValidationError as ex:
                self._validated_data = {}

                for field in ex.message_dict:
                    self._errors.update({field: ex.message_dict[field][0]})

        if self._errors and raise_exception:
            raise ValidationError(self.errors)

        return not bool(self._errors) 
开发者ID:mozilla,项目名称:normandy,代码行数:18,代码来源:serializers.py

示例2: run_validators

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def run_validators(validators: Iterable[Validator], value: Any) -> None:
    fields_errors = OrderedDict()  # type: Dict[str, Any]
    non_field_errors = []  # type: List[Any]
    for validator in validators:
        try:
            validator(value)
        except ValidationError as exc:
            if isinstance(exc.detail, Mapping):
                for field_name, field_errors in exc.detail.items():
                    fields_errors.setdefault(field_name, []).extend(
                        field_errors)
            elif isinstance(exc.detail, list):
                non_field_errors.extend(exc.detail)

    if fields_errors:
        errors = {}
        errors.update(fields_errors)
        errors.setdefault(
            api_settings.NON_FIELD_ERRORS_KEY, []).extend(non_field_errors)
        raise ValidationError(errors)
    if non_field_errors:
        # TODO: Issue #109 - remove type: ignore
        raise ValidationError(non_field_errors)  # type: ignore 
开发者ID:apragacz,项目名称:django-rest-registration,代码行数:25,代码来源:validation.py

示例3: get_value

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def get_value(self, data):
        if isinstance(data, MultiValueDict):
            regex = re.compile(r"^%s\.(.*)$" % re.escape(self.field_name))
            ret = {}
            for name, value in data.items():
                match = regex.match(name)
                if not match:
                    continue
                key = match.groups()[0]
                if value != '':
                    ret[key] = value
        elif isinstance(data, dict):
            ret = data.get(self.field_name, fields.empty)
        else:
            raise ValidationError("not a dict: " + str(type(data)))

        if ret is fields.empty or len(ret) == 0:
            return fields.empty
        return ret 
开发者ID:qwiglydee,项目名称:drf-mongo-filters,代码行数:21,代码来源:fields.py

示例4: to_internal_value

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def to_internal_value(self, data):
        if not hasattr(data, '__getitem__') or not hasattr(data, 'items'):
            raise ValidationError("not a dict: " + str(type(data)))

        keys = set(data.keys())
        if self.valid_keys is not None:
            if not keys <= self.valid_keys:
                raise ValidationError("invalid keys in dict: " + str(keys))

        if self.required_keys is not None:
            if not keys >= self.required_keys:
                raise ValidationError("missing required keys in dict: " + str(keys))

        return dict([
            (str(key), self.child.run_validation(value))
            for key, value in data.items()
        ]) 
开发者ID:qwiglydee,项目名称:drf-mongo-filters,代码行数:19,代码来源:fields.py

示例5: create_provider

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def create_provider(self, name, provider_type, authentication, billing_source, source_uuid=None):
        """Call to create provider."""
        connection.set_schema_to_public()
        context, customer, user = self._create_context()
        tenant = Tenant.objects.get(schema_name=customer.schema_name)
        json_data = {
            "name": name,
            "type": provider_type.lower(),
            "authentication": self.get_authentication_for_provider(provider_type, authentication),
            "billing_source": self.get_billing_source_for_provider(provider_type, billing_source),
        }
        if source_uuid:
            json_data["uuid"] = str(source_uuid)

        connection.set_tenant(tenant)
        serializer = ProviderSerializer(data=json_data, context=context)
        try:
            if serializer.is_valid(raise_exception=True):
                instance = serializer.save()
        except ValidationError as error:
            connection.set_schema_to_public()
            raise error
        connection.set_schema_to_public()
        return instance 
开发者ID:project-koku,项目名称:koku,代码行数:26,代码来源:provider_builder.py

示例6: test_create_provider_fails_customer

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_create_provider_fails_customer(self):
        """Test creating a provider where customer is not found for user."""
        provider = {
            "name": "test_provider",
            "type": Provider.PROVIDER_AWS.lower(),
            "authentication": {"provider_resource_name": "arn:aws:s3:::my_s3_bucket"},
            "billing_source": {"bucket": "my_s3_bucket"},
        }
        user_data = self._create_user_data()
        alt_request_context = self._create_request_context(
            self.create_mock_customer_data(), user_data, create_tenant=True
        )
        request = alt_request_context["request"]
        request.user.customer = None
        serializer = ProviderSerializer(data=provider, context=alt_request_context)
        if serializer.is_valid(raise_exception=True):
            with self.assertRaises(serializers.ValidationError):
                serializer.save() 
开发者ID:project-koku,项目名称:koku,代码行数:20,代码来源:tests_serializers.py

示例7: test_create_provider_with_credentials_and_provider_resource_name

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_create_provider_with_credentials_and_provider_resource_name(self):
        """Test creating a provider with credentials and provider_resource_name fields should fail."""
        iam_arn = "arn:aws:s3:::my_s3_bucket"
        provider = {
            "name": "test_provider",
            "type": Provider.PROVIDER_AWS.lower(),
            "authentication": {"credentials": {"one": "two", "three": "four"}, "provider_resource_name": iam_arn},
            "billing_source": {"data_source": {"foo": "bar"}},
        }
        user_data = self._create_user_data()
        alt_request_context = self._create_request_context(
            self.create_mock_customer_data(), user_data, create_tenant=True
        )
        request = alt_request_context["request"]
        request.user.customer = None
        serializer = ProviderSerializer(data=provider, context=alt_request_context)
        if serializer.is_valid(raise_exception=True):
            with self.assertRaises(serializers.ValidationError):
                serializer.save() 
开发者ID:project-koku,项目名称:koku,代码行数:21,代码来源:tests_serializers.py

示例8: test_create_provider_with_bucket_and_data_source

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_create_provider_with_bucket_and_data_source(self):
        """Test creating a provider with data_source and bucket fields should fail."""
        bucket_name = "my_s3_bucket"
        provider = {
            "name": "test_provider",
            "type": Provider.PROVIDER_AWS.lower(),
            "authentication": {"credentials": {"one": "two", "three": "four"}},
            "billing_source": {"data_source": {"foo": "bar"}, "bucket": bucket_name},
        }
        user_data = self._create_user_data()
        alt_request_context = self._create_request_context(
            self.create_mock_customer_data(), user_data, create_tenant=True
        )
        request = alt_request_context["request"]
        request.user.customer = None
        serializer = ProviderSerializer(data=provider, context=alt_request_context)
        if serializer.is_valid(raise_exception=True):
            with self.assertRaises(serializers.ValidationError):
                serializer.save() 
开发者ID:project-koku,项目名称:koku,代码行数:21,代码来源:tests_serializers.py

示例9: test_missing_creds_parameters_exception

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_missing_creds_parameters_exception(self):
        """Test that ValidationError is raised when there are missing parameters."""
        fields = ["subscription_id", "tenant_id", "client_id", "client_secret"]
        credentials = {
            "subscription_id": FAKE.uuid4(),
            "tenant_id": FAKE.uuid4(),
            "client_id": FAKE.uuid4(),
            "client_secret": FAKE.word(),
        }
        source_name = {"resource_group": FAKE.word(), "storage_account": FAKE.word()}
        del credentials[random.choice(fields)]

        provider = {
            "name": FAKE.word(),
            "type": Provider.PROVIDER_AZURE.lower(),
            "authentication": {"credentials": credentials},
            "billing_source": {"data_source": source_name},
        }

        with self.assertRaises(ValidationError):
            serializer = ProviderSerializer(data=provider, context=self.request_context)
            serializer.is_valid(raise_exception=True) 
开发者ID:project-koku,项目名称:koku,代码行数:24,代码来源:tests_serializers.py

示例10: test_missing_source_parameters_exception

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_missing_source_parameters_exception(self):
        """Test that ValidationError is raised when there are missing parameters."""
        fields = ["resource_group", "storage_account"]
        credentials = {
            "subscription_id": FAKE.uuid4(),
            "tenant_id": FAKE.uuid4(),
            "client_id": FAKE.uuid4(),
            "client_secret": FAKE.word(),
        }
        source_name = {"resource_group": FAKE.word(), "storage_account": FAKE.word()}
        del source_name[random.choice(fields)]

        provider = {
            "name": FAKE.word(),
            "type": Provider.PROVIDER_AZURE.lower(),
            "authentication": credentials,
            "billing_source": {"data_source": source_name},
        }

        with self.assertRaises(ValidationError):
            serializer = ProviderSerializer(data=provider, context=self.request_context)
            serializer.is_valid(raise_exception=True) 
开发者ID:project-koku,项目名称:koku,代码行数:24,代码来源:tests_serializers.py

示例11: test_create_gcp_provider_validate_report_prefix_too_long

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_create_gcp_provider_validate_report_prefix_too_long(self):
        """Test the data_source.report_prefix validation for GCP provider."""
        provider = {
            "name": "test_provider_val_data_source",
            "type": Provider.PROVIDER_GCP.lower(),
            "authentication": {"credentials": {"project_id": "gcp_project"}},
            "billing_source": {
                "data_source": {
                    "bucket": "precious-taters",
                    "report_prefix": "an-unnecessarily-long-prefix-that-is-here-simply-for-the-purpose-of"
                    "testing-the-custom-validator-the-checks-for-too-long-of-a-report_prefix",
                }
            },
        }

        with self.assertRaises(ValidationError) as e:
            serializer = ProviderSerializer(data=provider, context=self.request_context)
            serializer.is_valid(raise_exception=True)

        self.assertEqual(e.exception.status_code, 400)
        self.assertEqual(
            str(e.exception.detail["billing_source"]["data_source.report_prefix"][0]),
            f"Ensure this field has no more than {REPORT_PREFIX_MAX_LENGTH} characters.",
        ) 
开发者ID:project-koku,项目名称:koku,代码行数:26,代码来源:tests_serializers.py

示例12: test_create_gcp_provider_duplicate_bucket

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_create_gcp_provider_duplicate_bucket(self):
        """Test that the same blank billing entry is used for all OCP providers."""
        provider = {
            "name": "test_provider_one",
            "type": Provider.PROVIDER_GCP.lower(),
            "authentication": {"credentials": {"project_id": "gcp_project"}},
            "billing_source": {"data_source": {"bucket": "test_bucket"}},
        }
        with patch.object(ProviderAccessor, "cost_usage_source_ready", returns=True):
            serializer = ProviderSerializer(data=provider, context=self.request_context)
            if serializer.is_valid(raise_exception=True):
                serializer.save()

            with self.assertRaises(ValidationError):
                serializer = ProviderSerializer(data=provider, context=self.request_context)
                if serializer.is_valid(raise_exception=True):
                    serializer.save() 
开发者ID:project-koku,项目名称:koku,代码行数:19,代码来源:tests_serializers.py

示例13: test_create_provider_invalid_type

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def test_create_provider_invalid_type(self):
        """Test that an invalid provider type is not validated."""
        iam_arn = "arn:aws:s3:::my_s3_bucket"
        bucket_name = "my_s3_bucket"
        provider = {
            "name": "test_provider",
            "type": "Bad",
            "authentication": {"provider_resource_name": iam_arn},
            "billing_source": {"bucket": bucket_name},
        }

        with patch.object(ProviderAccessor, "cost_usage_source_ready", returns=True):
            with self.assertRaises(ValidationError):
                serializer = ProviderSerializer(data=provider, context=self.request_context)
                if serializer.is_valid(raise_exception=True):
                    serializer.save() 
开发者ID:project-koku,项目名称:koku,代码行数:18,代码来源:tests_serializers.py

示例14: create_user

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def create_user(username, email, customer, request):
        """Create a user for a customer.
        Args:
            username (str): The username
            email (str): The email for the user
            customer (Customer): The customer the user is associated with
            request (object): The incoming request
        Returns:
            (User) The created user
        """
        new_user = None
        try:
            with transaction.atomic():
                user_data = {"username": username, "email": email}
                context = {"request": request, "customer": customer}
                serializer = UserSerializer(data=user_data, context=context)
                if serializer.is_valid(raise_exception=True):
                    new_user = serializer.save()

                UNIQUE_USER_COUNTER.labels(account=customer.account_id, user=username).inc()
                LOG.info("Created new user %s for customer(account_id %s).", username, customer.account_id)
        except (IntegrityError, ValidationError):
            new_user = User.objects.get(username=username)
        return new_user 
开发者ID:project-koku,项目名称:koku,代码行数:26,代码来源:middleware.py

示例15: __init__

# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ValidationError [as 别名]
def __init__(self, task, customer_name, billing_source, **kwargs):
        """
        Constructor.

        Args:
            task           (Object) bound celery object
            customer_name  (str): Name of the customer
            billing_source (dict): dict containing name of GCP storage bucket

        """
        super().__init__(task, **kwargs)

        self.bucket_name = billing_source["bucket"]
        self.report_prefix = billing_source.get("report_prefix", "")
        self.customer_name = customer_name.replace(" ", "_")
        self._provider_uuid = kwargs.get("provider_uuid")

        try:
            GCPProvider().cost_usage_source_is_reachable(None, billing_source)
            self._storage_client = storage.Client()
            self._bucket_info = self._storage_client.lookup_bucket(self.bucket_name)
        except ValidationError as ex:
            msg = f"GCP bucket {self.bucket_name} for customer {customer_name} is not reachable. Error: {str(ex)}"
            LOG.error(log_json(self.request_id, msg, self.context))
            raise GCPReportDownloaderError(str(ex)) 
开发者ID:project-koku,项目名称:koku,代码行数:27,代码来源:gcp_report_downloader.py


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