Exemple #1
0
    def __init__(self, enum=None, *args, **kwargs):
        if enum is not None:
            self.enum = enum
        elif self.enum is None:
            raise ValueError("`enum` must be specified")

        Field.__init__(self, *args, **kwargs)
Exemple #2
0
    def _bind_field(self, field_name: str, field_obj: ma_fields.Field) -> None:
        """Bind field to the schema, setting any necessary attributes on the
        field (e.g. parent and name).

        Also set field load_only and dump_only values if field_name was
        specified in ``class Meta``.
        """
        if field_name in self.load_only:
            field_obj.load_only = True
        if field_name in self.dump_only:
            field_obj.dump_only = True
        try:
            field_obj._bind_to_schema(field_name, self)
        except TypeError as error:
            # Field declared as a class, not an instance. Ignore type checking because
            # we handle unsupported arg types, i.e. this is dead code from
            # the type checker's perspective.
            if isinstance(field_obj, type) and issubclass(field_obj, base.FieldABC):
                msg = (
                    'Field for "{}" must be declared as a '
                    "Field instance, not a class. "
                    'Did you mean "fields.{}()"?'.format(field_name, field_obj.__name__)
                )
                raise TypeError(msg) from error
            raise error
        self.on_bind_field(field_name, field_obj)
Exemple #3
0
def validate_value(*, field: mfields.Field, value: Any):
    """
    Invokes the field's validator, if exists and it is callable.
    Note: multiple validators are not currently supported as an iterable, but rather as a single
    validation function that and-s between the validators' results.
    """
    if field.validate is not None and callable(field.validate):
        field.validate(value)
Exemple #4
0
 def _serialize_field(self, data, field: fields.Field):
     result = {}
     for key, value in data.items():
         field._validate(value)
         try:
             result[key] = field.serialize(obj=data, attr=key)
         except ValueError as exc:
             raise ValidationError(str(exc), field_name=key)
     return result
Exemple #5
0
def deserialize_field(marshmallow_field: fields.Field, value: Any) -> Any:
    """
    Deserialize filter/sort value
    :param marshmallow_field: marshmallow field type
    :param value: filter/sort value
    :return:
    """
    try:
        if isinstance(value, list) and type(marshmallow_field) in STANDARD_MARSHMALLOW_FIELDS:
            return [marshmallow_field.deserialize(i_value) for i_value in value]
        if not isinstance(value, list) and isinstance(marshmallow_field, fields.List):
            return marshmallow_field.deserialize([value])
        return marshmallow_field.deserialize(value)
    except ValidationError:
        raise InvalidFilters(f'Bad filter value: {value!r}')
 def _deserialize_field(value, field: Field):
     if value is None:
         if field.default:
             return field.default
         if field.required:
             raise SchemaOrFieldDeserializer.RequiredFieldNotSetException()
     else:
         return field.deserialize(value)
Exemple #7
0
    def on_bind_field(self, field_name: str, field_obj: fields.Field) -> None:
        """Modify a field when it is bound to the schema.

        Automatically convert all schema fields to their camelCase representations.

        Args:
            field_name: The name of the field
            field_obj: The field object

        """
        # https://marshmallow.readthedocs.io/en/latest/examples.html#inflection-camel-casing-keys
        field_obj.data_key = camelcase(field_obj.data_key or field_name)
 def all_args_spec(self, req=None, *args, **kwargs):
     req = req or request
     locations = kwargs.get('locations', []) or self.locations
     spec = {}
     for location in locations:
         if location == 'json':
             json_dict = req.get_json(silent=True)
             if json_dict:
                 [spec.__setitem__(k, Field()) for k in json_dict.keys()]
         elif location == 'querystring':
             [spec.__setitem__(k, Field()) for k in req.args.keys()]
         elif location == 'form':
             [spec.__setitem__(k, Field()) for k in req.form.keys()]
         elif location == 'headers':
             [spec.__setitem__(k, Field()) for k in req.headers.keys()]
         elif location == 'cookies':
             [spec.__setitem__(k, Field()) for k in req.cookies.keys()]
         elif location == 'files':
             [spec.__setitem__(k, Field()) for k in req.files.keys()]
         else:
             pass
     return spec
 class Model(model_base.ModelBase):
     externalField = Field(external=True)
     noneInternalField = Field(internal=False)
     field = Field(allow_none=True)
Exemple #10
0
 def on_bind_field(self, field_name: str, field_obj: Field) -> None:
     field_obj.data_key = camelcase(field_obj.data_key or field_name)
 def serialize(self, attr, obj, accessor=None):
     """Overrides change done from 2.10.2->2.10.3 in https://github.com/marshmallow-code/marshmallow/commit/d81cab413e231ec40123020f110a8c0af22163ed.
     """
     ret = Field.serialize(self, attr, obj, accessor=accessor)
     return self._to_string(ret) if (self.as_string
                                     and ret is not None) else ret
Exemple #12
0
 class Schema(BaseSchema):
     excluded1 = Field()
     excluded2 = Field(exclude_this=True)
     excluded3 = Field(exclude_this=True)
     included = Field()
Exemple #13
0
 def on_bind_field(self, field_name: str, field_obj: fields.Field):
     field_obj.data_key = camelcase(field_obj.data_key or field_name)
Exemple #14
0
 def _deserialize_field(self, data, field: fields.Field):
     result = {}
     for key, value in data.items():
         field._validate(value)
         result[key] = field.deserialize(value=value, data=data, attr=key)
     return result
Exemple #15
0
 def on_bind_field(self, field_name: str, field_obj: fields.Field) -> None:
     field_obj.data_key = BaseSchema._from_snake_to_camel(field_obj.data_key
                                                          or field_name)