Exemple #1
0
    def validate(self, value):
        if value is None and self._does_allow_none():
            return None
        if type(value) is datetime.date:
            return value

        if type(value) is datetime.datetime:
            return datetime.date(value.year, value.month, value.day)

        if isinstance(value, datetime.date) or isinstance(value, datetime.datetime):
            return datetime.date(value.year, value.month, value.day)

        try:
            dt = parse_datetime(value)
            if dt:
                return datetime.date(dt.year, dt.month, dt.day)
        except (ValueError, TypeError):
            dt = None

        if not dt:
            try:
                dt = parse_date(value)
            except (ValueError, TypeError):
                raise FieldValidationError(FieldError(self, 'invalid'))

        if dt:
            return dt
        raise FieldValidationError(FieldError(self, 'invalid'))
Exemple #2
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     if type(value) is not str or str(value) != value:
         raise FieldValidationError(FieldError(self, 'invalid'))
     if self.trim:
         value = value.strip()
     if not value and not self.allow_empty:
         raise FieldValidationError(FieldError(self, 'empty'))
     return value
Exemple #3
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     schema = self.cached or self._get_schema()
     if not hasattr(value, '__dict__') and (type(value) is not dict or not isinstance(value, dict)):
         raise FieldValidationError(FieldError(self, 'invalid_mapping'))
     try:
         return schema.validate(value, exclude=self.exclude, whitelist=self.whitelist, tags=self.tags,
                                halt_on_error=self._schema.halt_on_error)
     except ValidationError:
         raise FieldValidationError(FieldError(self, 'invalid', errors=schema._raw_errors))
Exemple #4
0
    def _validate_element(self, field, key, klass_value, output_missing,
                          allow_none):
        # run pre validation functions
        pre_validate = self._field_callables.pre_validate
        if pre_validate:
            for func in pre_validate.get(key, []):
                try:
                    klass_value = func(klass_value, schema=self, field=field)
                except FieldValidationError as field_exc:
                    self._error_handler.add(key, field_exc.error)
                    break

        if self.errors and self.halt_on_error:
            return klass_value

        missing = (klass_value is SchemaFieldMissing)

        # if the field is missing, but it's required, set an error.
        # if a value of None is allowed and we do not have a field, skip validation
        # otherwise, validate the value
        if missing:
            if field.required:
                self._error_handler.add(key, FieldError(field, 'required'))
            elif not allow_none:
                self._error_handler.add(
                    key,
                    FieldError(field,
                               'required' if field.required else 'invalid'))
        elif klass_value is None:
            if not output_missing and not allow_none:
                self._error_handler.add(
                    key,
                    FieldError(field,
                               'required' if field.required else 'invalid'))
        else:
            try:
                klass_value = field.validate(klass_value)
            except FieldValidationError as field_exc:
                self._error_handler.add(key, field_exc.error)

        # run post validation functions
        post_validate = self._field_callables.post_validate
        if post_validate:
            for validator in post_validate.get(key, []):
                try:
                    klass_value = validator(klass_value,
                                            schema=self,
                                            field=field)
                except FieldValidationError as field_exc:
                    self._error_handler.add(key, field_exc.error)
                    break

        return klass_value
Exemple #5
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     if isinstance(value, datetime.date):
         return value
     try:
         dt = parse_datetime(value)
         if dt:
             return dt
         raise FieldValidationError(FieldError(self, 'invalid'))
     except (ValueError, TypeError):
         raise FieldValidationError(FieldError(self, 'invalid'))
Exemple #6
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     if type(value) is int:
         return value
     try:
         if not float(value).is_integer():
             raise FieldValidationError(FieldError(self, 'invalid'))
     except (TypeError, ValueError):
         raise FieldValidationError(FieldError(self, 'invalid'))
     try:
         if int(value) != value or type(value) is bool:
             raise FieldValidationError(FieldError(self, 'invalid'))
     except ValueError:
         raise FieldValidationError(FieldError(self, 'invalid'))
     return value
Exemple #7
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     if type(value) is float:
         return value
     if type(value) in (bool, str):
         raise FieldValidationError(FieldError(self, 'invalid'))
     try:
         float(value) is value
     except TypeError:
         raise FieldValidationError(FieldError(self, 'invalid'))
     if self.strict:
         try:
             value.is_integer()
         except AttributeError:
             raise FieldValidationError(FieldError(self, 'invalid'))
     return value
Exemple #8
0
 def validate(self, value):
     self.field._schema = self._schema
     if value is None and self._does_allow_none():
         return None
     valid = []
     errors = {}
     if not isinstance(value, list):
         raise FieldValidationError(FieldError(self, 'invalid'))
     for k, v in enumerate(value):
         try:
             valid.append(self.field.validate(v))
         except FieldValidationError as field_exc:
             errors[str(k)] = field_exc.error
             if self._schema.halt_on_error:
                 break
     if errors:
         raise FieldValidationError(FieldError(self, 'invalid_item', errors=errors))
     return valid
Exemple #9
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     try:
         return uuid.UUID(value)
     except (ValueError, AttributeError, TypeError):
         pass
     if isinstance(value, uuid.UUID):
         return value
     raise FieldValidationError(FieldError(self, 'invalid'))
Exemple #10
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     valid = False
     for field in self.fieldset:
         field._schema = self._schema
         try:
             value = field.validate(value)
             valid = True
             break
         except Exception:
             continue
     if not valid:
         raise FieldValidationError(FieldError(self, 'invalid'))
     return value
Exemple #11
0
    def _iterate(
        self,
        data,
        exclude=None,
        whitelist=None,
        tags=None,
        do_validate=False,
        do_deserialize=False,
        do_serialize=False
    ):
        output_missing = self._config.output_missing
        allow_none = self._config.allow_none

        if do_validate:
            self._error_handler.reset()

        # get elements
        if tags:
            data_keys = []
            for tag in tags:
                data_keys.extend(self._tags.get(tag, []))
            elements = set(data_keys)
        elif whitelist:
            elements = set(whitelist)
        else:
            data_keys = []
            for k in data:
                if self._fields.get(k):
                    data_keys.append(k)
                elif self._load_keys.get(k):
                    data_keys.extend(self._load_keys[k])
            elements = set(self._check_elements + data_keys)

        exclude = set(exclude) if exclude else set()

        output = {}
        for key in elements:
            if key in exclude:
                continue

            field = self._fields[key]

            if field.output_missing is not UseSchemaOption:
                output_missing = field.output_missing
            if field.allow_none is not UseSchemaOption:
                allow_none = field.allow_none

            # field value
            if do_serialize:
                klass_value = data.get(key, SchemaFieldMissing)
            elif do_deserialize or do_validate:
                load_key = getattr(field, 'load', None) or key
                klass_value = data.get(load_key, SchemaFieldMissing)
            if do_validate and klass_value is SchemaFieldMissing:
                klass_value = data.get(key, SchemaFieldMissing)

            missing = (klass_value is SchemaFieldMissing)

            # if we encounter a schema field, cache it
            if key in self._pending_schemas:
                self._subschemas[key] = field._get_schema()
                self._pending_schemas.pop(key)

            if key in self._subschemas and klass_value is not None and not missing:
                subschema = self._subschemas[key]  # reference the subschema
                if isinstance(subschema, AbstractPolySchema):
                    try:
                        polykey = subschema.getpolyname()
                        if hasattr(klass_value, '__dict__'):
                            klass_value = vars(klass_value)
                        subschema.getpoly(klass_value[polykey])()
                    except Exception:
                        self._error_handler.add(key, FieldError(field, 'invalid_polykey'))
                        continue

            # if the field is missing and we do not output_missing skip it
            if not field.required and missing and not output_missing:
                continue

            if output_missing:
                # if the field is missing, set the default value
                if (missing or klass_value is None) and (field.default is not SchemaFieldDefault):
                    if callable(field.default):
                        klass_value = field.default(self, field)
                    else:
                        klass_value = field.default
                    missing = False

                # if fields are not required, but missing and
                # we allow them in the output, set the value to
                # the field missing output value
                if not field.required and missing:
                    klass_value = field.missing_output_value

            if do_validate:
                # sets klass_value prior to serialization/deserialization
                output[key] = klass_value = self._validate_element(field, key, klass_value, output_missing, allow_none)
                if self.errors and self.halt_on_error:
                    break
                elif self.errors:
                    continue

            if do_serialize:
                # determine the field result name (serialized name)
                output_key = field.name or key

                output[output_key] = self._serialize_element(field, output_key, klass_value)

                # remove old keys if the serializer renames the field
                if output_key != key:
                    del output[key]

            if do_deserialize:
                output[key] = self._deserialize_element(field, key, klass_value)

        return output
Exemple #12
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     if not isinstance(value, dict):
         raise FieldValidationError(FieldError(self, 'invalid'))
     return value
Exemple #13
0
 def validate(self, value):
     if value is None and self._does_allow_none():
         return None
     if type(value) is not bool:
         raise FieldValidationError(FieldError(self, 'invalid'))
     return value