def to_internal_value(self, data):
        """
        Data transformation to python list object.

        :param object data: Data for transformation.

        :return: Transformed data.
        :rtype: list

        :raise ValidationError: If data not valid.

        """
        # Parse data.
        if html.is_html_input(data):
            data = html.parse_html_list(data)

        # Initial validation that came in an array.
        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(detail={'non_field_errors': [message]},
                                  code='not_a_list')

        # Validation that this is not an empty value and whether it is empty.
        if not self.allow_empty and len(data) == 0:
            message = self.error_messages['empty']
            raise ValidationError(detail={'non_field_errors': [message]},
                                  code='empty')

        res, errors = [], []  # Make storage for results.

        # Validating each item from the list.
        for item in data:
            try:
                value = self.child.run_validation(item)
            except ValidationError as e:
                res.append({})
                errors.append(e.detail)
            else:
                res.append(value)
                errors.append({})

        # If the conversion and validation failed.
        if any(errors):
            raise ValidationError(detail=errors)

        # We return the transformed and validated data.
        return res
Beispiel #2
0
    async def get_valid_json(self, parse_query=False, raise_exception=True):
        """
        Make, Validate and return JSON from request BODY.

        :param bool parse_query: Parse query or only body?
        :param bool raise_exception: Raise exception if body not parse?

        :return: Validated data from request BODY.
        :rtype: Optional[dict]

        """
        # Get request query
        data = self.request_object.query.copy() if parse_query else {}
        # Get request body
        try:
            request_json = await self.request_object.json()
            data.update(request_json)
        except JSONDecodeError:
            if raise_exception:
                raise ValidationError(detail='Not valid json.')

        # Validate body request.
        serializer = self.get_request_serializer()
        if serializer is None:
            return None
        serializer = serializer(data=data)
        serializer.is_valid(raise_exception=True)

        return serializer.validated_data
Beispiel #3
0
    def validate_empty_values(self, data):
        """
        Check if the value is empty.

        :param object data: Data for check.

        :return: The result of check, and current data.
                 If there is a default value and nothing is passed, returns the default.
                 Tuple: (is None, actual data)
        :rtype: tuple

        :raise ValidationError: If validation on an empty field did not pass.

        """
        # Process.
        is_empty, data = data is None, data if data is not None else self.default

        # Validating.
        if is_empty and not self.required:
            return is_empty, data

        # If empty and not necessary, then there is nothing to validate and transformed.
        if is_empty:
            raise ValidationError(detail=self.error_messages['required'])

        # Return.
        return is_empty, data
    def is_valid(self, raise_exception=False):
        """
        Validates the data that came into the serializer.

        :param bool raise_exception: Is there an exception if validation fails?

        :return: Validation result.
        :rtype: bool

        """
        if not hasattr(self, 'initial_data'):
            raise AssertionError(
                'Cannot call `.is_valid()` as no `data=` keyword argument '
                'was passed when instantiating the serializer instance.')

        # Preparing storage for results.
        self._errors, self._validated_data = [], []

        # Validating all fields
        try:
            self._validated_data = self.to_internal_value(self.initial_data)
        except ValidationError as e:
            self._errors = e.detail

        # If you need to throw an error, we throw.
        if self._errors and raise_exception:
            self._validated_data = []
            raise ValidationError(detail=self._errors)

        # Return validation result.
        return not bool(self._errors)
    def run_validation(self, data):
        """
        Runs validation on the current serializer..

        :param object data: Data for validation.

        :return: Transformed and validated data.
        :rtype: dict

        """
        # We first check to see if an empty field has arrived?
        is_empty, data = self.validate_empty_values(data)

        # Transformed to python type.
        value = self.to_internal_value(data)

        # Validating validators.
        try:
            self.run_validators(value)
            value = self.validate(value)
            assert value is not None, '`.validate ()` should return a valid value.'

        except ValidationError as e:
            raise ValidationError(detail=e.detail)

        # We return the validated and transformed value.
        return value
Beispiel #6
0
    def __call__(self, value: object):
        """
        Validation.

        :param object value: Object for validation.

        """
        if value not in self.choices:
            raise ValidationError(
                self.message.format(**dict(allowed_values=self.choices)))
Beispiel #7
0
    def __call__(self, value):
        """
        Validation.

        :param iter value: Object for validation.

        :raise ValidationError: If not valid data.

        """
        if value is None:
            raise ValidationError(self.message)
Beispiel #8
0
    def fail_validate(self, detail=None, status=400):
        """
        We throw a normal error if custom validation error.

        :param Union[str, dict] detail: Detail validation error
        :param int status: Code for response

        :raise AssertionError: If you have not found the key in the `self.error_messages`.
        :raise ValidationError: If you find the key in the `self.error_messages`.

        """
        raise ValidationError(detail=detail, status=status)
Beispiel #9
0
    def __call__(self, value):
        """
        Validation.

        :param iter value: Object for validation.

        :raise ValidationError: If not valid data.

        """
        if len(value) < self.min_length:
            raise ValidationError(
                self.message.format(min_length=self.min_length))
Beispiel #10
0
    def __call__(self, value):
        """
        Validate that the input contains a match for the regular expression
        if inverse_match is False, otherwise raise ValidationError.

        :param object value: Value for validation.

        :raise: ValidationError: If not valid data.

        """
        if not (self.inverse_match is not bool(self.regex.search(value))):
            raise ValidationError(self.message)
Beispiel #11
0
    def __call__(self, value):
        """
        Validation.

        :param object value: Value for validation.

        :raise ValidationError: If not valid data.

        """
        if value > self.max_value:
            raise ValidationError(
                self.message.format(max_value=self.max_value))
    def _field_validation(self, fields_dict, data):
        """
        Validation add fields

        :param dict fields_dict: Dictionary with initialized fields that we validate.
        :param dict data: Data that is validated.

        :return: Validated and transformed data.
        :raise ValidationError: If errors occurred during validation.

        """
        validated_data, errors = OrderedDict(), OrderedDict()
        # Running through the fields.
        for _, field_obj in six.iteritems(fields_dict):
            field_name = field_obj._get_field_name()
            try:
                # Check by empty for nested serializer fields
                is_empty, _field_data = field_obj.validate_empty_values(
                    data.get(field_name, None))
                if is_empty:
                    if field_name in data:
                        validated_data[field_name] = _field_data
                    continue

                # Transform to python type and validate each field.
                validated_val = field_obj.run_validation(_field_data)

                # Now manual validation.
                validated_val = self._manual_validate_method(
                    field_name, validated_val)

                # And if there was a field in the incoming data, then we save it in the converted form.
                if field_name in data:
                    validated_data[field_name] = validated_val
                elif field_obj.default:
                    validated_data[field_name] = field_obj.default

            except ValidationError as e:
                # If not passed validation, save the error.
                errors[field_name] = e.detail
            except (AttributeError, TypeError, ValueError):
                # If data not valid format.
                errors[
                    field_name] = 'Could not parse data for field `{}`.'.format(
                        field_name)

        if any(errors):
            raise ValidationError(detail=errors)

        return validated_data
Beispiel #13
0
    def run_validators(self, value):
        """
        Validates all field validators.

        :param object value: Data for validation.

        :raise ValidationError: If validation fails.

        """
        errors = []

        for validator in self.validators or []:
            try:
                # Run each validator.
                validator(value)
            except ValidationError as e:
                errors.append(e.detail)

        # Check on errors.
        if errors:
            raise ValidationError(detail=errors)
    def is_valid(self, raise_exception=False):
        """
        Validates the data that came into the serializer.

        :param bool raise_exception: Whether to throw an exception if validation failed?

        :return: Validation result.
        :rtype: bool

        """
        if not hasattr(self, 'initial_data'):
            raise AssertionError(
                'Cannot call `.is_valid()` as no `data=` keyword argument '
                'was passed when instantiating the serializer instance.')

        # Preparing storage for results.
        self._errors, self._validated_data = OrderedDict(), OrderedDict()

        # Validated all fields.
        try:
            self._validated_data = self._field_validation(
                self.fields, self.initial_data)
        except ValidationError as e:
            self._errors = e.detail

        # Now run the full manual validation method.
        try:
            self._validated_data = self.validate(
                self._validated_data
            ) if not self._errors else self._validated_data
        except ValidationError as e:
            self._errors['errors'] = e.detail

        # If you need to throw an error, we throw.
        if self._errors and raise_exception:
            self._validated_data = OrderedDict()
            raise ValidationError(detail=self._errors)

        # Return validation result.
        return not bool(self._errors)
Beispiel #15
0
    def fail_field_validation(self, key, **kwargs):
        """
        We throw a normal error if something went wrong during data processing.

        :param str key: Error type. Key for dict `self.default_error_messages`.
        :param kwargs: Data to format error message.

        :raise AssertionError: If you have not found the key in the `self.error_messages`.
        :raise ValidationError: If you find the key in the `self.error_messages`.

        """
        # Trying to get an error message.
        try:
            msg = self.error_messages[key]
        except KeyError:
            # If we could not talk about it, I use a general message.
            class_name = self.__class__.__name__
            msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
            raise AssertionError(msg)

        # Format the message and throw an error.
        message_string = msg.format(**kwargs)
        raise ValidationError(detail=message_string, status=key)