Python rest_framework.exceptions.ValidationError() Examples
The following are 30
code examples of rest_framework.exceptions.ValidationError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.exceptions
, or try the search function
.
Example #1
Source File: middleware.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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
Example #2
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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()
Example #3
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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()
Example #4
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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()
Example #5
Source File: provider_builder.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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
Example #6
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #7
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #8
Source File: apis.py From hutils with MIT License | 6 votes |
def get_validation_error(message, data=None, code=None): """ 方便快捷抛 400 的函数。shortcut for raising bad request error in django-rest-framework. Examples:: raise get_validation_error('非法的请求') :rtype: rest_framework.exceptions.ValidationError """ try: from rest_framework.exceptions import ValidationError error = {"message": str(message)} if data is not None: error["data"] = data if code is not None: error["code"] = code return ValidationError(error) except ImportError: from django.core.exceptions import ValidationError return ValidationError(message=message, code=code, params=data)
Example #9
Source File: fields.py From drf-mongo-filters with GNU General Public License v2.0 | 6 votes |
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() ])
Example #10
Source File: fields.py From drf-mongo-filters with GNU General Public License v2.0 | 6 votes |
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
Example #11
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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.", )
Example #12
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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()
Example #13
Source File: tests_serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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()
Example #14
Source File: validation.py From django-rest-registration with MIT License | 6 votes |
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
Example #15
Source File: models.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def cancel(self): valid_choices = [ self.status_choices.RUN_QUEUED, self.status_choices.RUN_STARTED ] if self.status not in valid_choices: raise ValidationError({'status': ['Analysis is not running or queued']}) AsyncResult(self.run_task_id).revoke( signal='SIGKILL', terminate=True, ) self.status = self.status_choices.RUN_CANCELLED self.task_finished = timezone.now() self.save()
Example #16
Source File: staffSerializer.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def create(self, validated_data): bank_id = validated_data.pop('bank') if 'bank' in validated_data else None instance = Staff.objects.create(**validated_data) try: if bank_id: instance.bank = bank_id instance.bank_name = '' else: if instance.bank_name == "": raise ValidationError("Got empty bank name. Provide either bank id or bank name.") instance.save() except Exception as e: raise ValidationError("Got error on: {}".format(e)) return instance
Example #17
Source File: serializers.py From normandy with Mozilla Public License 2.0 | 6 votes |
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)
Example #18
Source File: test_analysis_model.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_state_is_running_or_generating_inputs___validation_error_is_raised_revoke_is_not_called(self, status, task_id): with TemporaryDirectory() as d: with override_settings(MEDIA_ROOT=d): res_factory = FakeAsyncResultFactory(target_task_id=task_id) initiator = fake_user() sig_res = Mock() with patch('src.server.oasisapi.analyses.models.Analysis.generate_input_signature', PropertyMock(return_value=sig_res)): analysis = fake_analysis(status=status, run_task_id=task_id, portfolio=fake_portfolio(location_file=fake_related_file())) with self.assertRaises(ValidationError) as ex: analysis.generate_inputs(initiator) self.assertEqual({'status': [ 'Analysis status must be one of [NEW, INPUTS_GENERATION_ERROR, INPUTS_GENERATION_CANCELLED, READY, RUN_COMPLETED, RUN_CANCELLED, RUN_ERROR]' ]}, ex.exception.detail) self.assertEqual(status, analysis.status) self.assertFalse(res_factory.revoke_called)
Example #19
Source File: test_analysis_model.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_portfolio_has_no_location_file___validation_error_is_raised_revoke_is_not_called(self, task_id): with TemporaryDirectory() as d: with override_settings(MEDIA_ROOT=d): res_factory = FakeAsyncResultFactory(target_task_id=task_id) initiator = fake_user() sig_res = Mock() with patch('src.server.oasisapi.analyses.models.Analysis.generate_input_signature', PropertyMock(return_value=sig_res)): analysis = fake_analysis(status=Analysis.status_choices.NEW, run_task_id=task_id) with self.assertRaises(ValidationError) as ex: analysis.generate_inputs(initiator) self.assertEqual({'portfolio': ['"location_file" must not be null']}, ex.exception.detail) self.assertEqual(Analysis.status_choices.NEW, analysis.status) self.assertFalse(res_factory.revoke_called)
Example #20
Source File: serializers.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 6 votes |
def validate(self, attrs): if 'HTTP_AUTHORIZATION' not in self.context['request'].META.keys(): raise ValidationError({"Detail": "header 'authorization' must not be null"}) token = self.context['request'].META['HTTP_AUTHORIZATION'][7:] # skip 'Bearer ' attrs['refresh'] = token data = super(TokenRefreshSerializer, self).validate(attrs) data['access_token'] = data['access'] data['token_type'] = 'Bearer' data['expires_in'] = jwt_settings.api_settings.ACCESS_TOKEN_LIFETIME.total_seconds() if 'refresh' in data: data['refresh_token'] = data['refresh'] del data['refresh'] del data['access'] return data
Example #21
Source File: gcp_report_downloader.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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))
Example #22
Source File: UserRoleViewsets.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def get_queryset(self): queryset = UserRole.objects.filter(organization__isnull=False) level = self.kwargs.get('level', None) pk = self.kwargs.get('pk', None) if level == "0": try: site = Site.objects.get(pk=pk) except Exception as e: raise ValidationError({ "No such site exists ".format(str(e)), }) queryset = queryset.filter(organization__id=site.project.organization_id).distinct('user_id') elif level == "1": try: project = Project.objects.get(pk=pk) except Exception as e: raise ValidationError({ "No such project exists ".format(str(e)), }) queryset = queryset.filter(organization__id=project.organization_id).distinct('user_id') elif level == "2": try: organization = Organization.objects.get(pk=pk) except Exception as e: raise ValidationError({ "No such organizations exists ".format(str(e)), }) queryset = queryset.filter(organization__id=organization.id).distinct('user_id') return queryset
Example #23
Source File: serializers.py From safe-relay-service with MIT License | 5 votes |
def validate_refund_receiver(self, refund_receiver): if refund_receiver and refund_receiver != NULL_ADDRESS: raise ValidationError('Refund Receiver is not configurable') return refund_receiver # ================================================ # # Responses # # ================================================ #
Example #24
Source File: serializers.py From safe-relay-service with MIT License | 5 votes |
def validate(self, data): super().validate(data) owners = data['owners'] threshold = data['threshold'] if threshold > len(owners): raise ValidationError("Threshold cannot be greater than number of owners") return data
Example #25
Source File: staffSerializer.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def create(self, validated_data): try: staffs = validated_data.pop('staffs') if 'staffs' in validated_data else [] if 'latitude' in validated_data and 'longitude' in validated_data: p = Point(float(validated_data.pop('longitude')), float(validated_data.pop('latitude')), srid=4326) validated_data.update({'location':p}) # else: # raise ValidationError("No location coordinates provided.") if not staffs: raise ValidationError("Got Empty staffs list.") else: for staff in staffs: if int(staff.team_id) != int(validated_data.get('team_id')): raise ValidationError("Got error on: Staffs entered has different team.") instance = Attendance.objects.create(**validated_data) instance.staffs = staffs instance.save() except Exception as e: raise ValidationError("Got error on: {}".format(e)) else: return instance
Example #26
Source File: serializers.py From KubeOperator with Apache License 2.0 | 5 votes |
def update(self, instance, validated_data): password = validated_data.pop('password') original = validated_data.pop('original') if instance.check_password(original): instance.set_password(password) return instance.save() else: raise ValidationError("original password error")
Example #27
Source File: test_kafka_listener.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def raise_validation_error(param_a, param_b, param_c, param_d, param_e): """Raise ValidationError""" raise ValidationError()
Example #28
Source File: test_kafka_source_manager.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_update_provider_error(self): """Test to update a provider with a koku server error.""" client = ProviderBuilder(auth_header=Config.SOURCES_FAKE_HEADER) source_uuid = faker.uuid4() with patch.object(ProviderAccessor, "cost_usage_source_ready", returns=True): client.create_provider( self.name, self.provider_type, self.authentication, self.billing_source, source_uuid ) with self.assertRaises(ValidationError): client.update_provider( source_uuid, "Aws Test", Provider.PROVIDER_AWS, {"resource_name": "arn:test"}, {"bucket": "bucket"} )
Example #29
Source File: models.py From linkedevents with MIT License | 5 votes |
def save(self, *args, **kwargs): if any([keyword.deprecated for keyword in self.keywords.all()]): raise ValidationError(_("KeywordSet can't have deprecated keywords")) super().save(*args, **kwargs)
Example #30
Source File: models.py From OasisPlatform with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cancel_generate_inputs(self): valid_choices = [ self.status_choices.INPUTS_GENERATION_QUEUED, self.status_choices.INPUTS_GENERATION_STARTED ] if self.status not in valid_choices: raise ValidationError({'status': ['Analysis input generation is not running or queued']}) self.status = self.status_choices.INPUTS_GENERATION_CANCELLED AsyncResult(self.generate_inputs_task_id).revoke( signal='SIGKILL', terminate=True, ) self.task_finished = timezone.now() self.save()