API Reference
- class serpyco.AbstractValidator(schema_builder)
Abstract class for schema validators. Implementation shall raise serpyco.ValidationError().
- json_schema(many=False)
Returns the schema that this validator uses to validate.
- Return type:
Dict
[str
,Any
]
- abstract validate(data, many=False)
Validates the given data against this object’s schema.
- Return type:
None
- abstract validate_json(json_string, many=False)
Validates a JSON string against this object’s schema.
- Return type:
None
- validate_user(data, many=False)
Validates the given data with the user-defined validators. See
serpyco.field()
. :type data:Union
[Dict
[str
,Any
],List
[Dict
[str
,Any
]]] :param data: data to validate, either a dict or a list of dicts (with many=True) :type many:bool
:param many: if true, data will be considered as a list- Return type:
None
- exception serpyco.BaseSerpycoError
- class serpyco.FieldEncoder
Base class for encoding fields to and from JSON encodable values
- dump()
Convert the given value to a JSON encodable value
- json_schema()
Return the JSON schema of the handled value type.
- load()
Convert the given JSON value to its python counterpart
- class serpyco.FieldHints(dict_key=None, ignore=False, getter=None, validator=None, description=None, examples=<factory>, format_=None, pattern=None, min_length=None, max_length=None, minimum=None, maximum=None, only=<factory>, exclude=<factory>, cast_on_load=False, allowed_values=<factory>, type_encoders=<factory>, load_as_type=None)
- exception serpyco.NoEncoderError
- exception serpyco.NotADataClassError
- class serpyco.SchemaBuilder(dataclass, only=None, exclude=None, type_encoders=None, get_definition_name=<function default_get_definition_name>, strict=False)
Creates a JSON schema by inspecting a dataclass
- json_schema(many=False)
Returns the json schema built from this SchemaBuilder’s dataclass.
- Return type:
Dict
[str
,Any
]
- nested_builders()
Returns a the list of nested builders this builder has created. Values are (definition name, builder) tuples.
- Return type:
List
[Tuple
[str
,SchemaBuilder
]]
- classmethod register_global_type(type_, encoder)
Can be used to register a custom encoder for the given type.
- Return type:
None
- classmethod unregister_global_type(type_)
Removes a previously registered encoder for the given type.
- Return type:
None
- exception serpyco.SchemaError
- class serpyco.Serializer
Serializer class for dataclasses instances.
- dataclass(self) type
Returns the dataclass used to construct this serializer.
- dump(self, obj: typing.Union[object, typing.Iterable[object]], bool validate: bool = False, bool many: bool = False)
Dumps the object(s) in the form of a dict/list only composed of builtin python types.
- Parameters:
validate – if True, the dumped data will be validated.
- dump_json(self, obj: typing.Union[object, typing.Iterable[object]], bool validate: bool = False, bool many: bool = False) unicode
Dumps the object(s) in the form of a JSON string.
- Parameters:
validate – if True, the dumped data will be validated
- f
alias of
UUID
- get_dict_path(self, obj_path: Sequence[str]) List[str]
Returns the path of a field in dumped dictionaries. :param obj_path: list of field names, for example [“foo”, “bar”] to get the dict path of foo.bar
- get_object_path(self, dict_path: Sequence[str]) List[str]
Returns the path of a field in loaded objects. :param dict_path: list of dictionary keys, for example [“foo”, “bar”] to get the object path of {“foo”: {“bar”: 42}}
- json_schema(self, many: bool = False) JsonDict
Returns the JSON schema of the underlying validator.
- load(self, data: typing.Union[dict, typing.Iterable[dict]], bool validate: bool = True, bool many: bool = False)
Loads the given data and returns object(s) of this serializer’s dataclass.
- Parameters:
validate – if True, the data will be validated before creating objects
- load_json(self, unicode js, bool validate: bool = True, bool many: bool = False)
Loads the given JSON string and returns object(s) of this serializer’s dataclass.
- Parameters:
validate – if True, the JSON will be validated before creating objects
- register_global_type(type cls, field_type: typing.Any, FieldEncoder encoder: FieldEncoder) None
Registers a encoder/decoder for the given type.
- unregister_global_type(type cls, field_type: typing.Any) None
Removes a previously registered encoder for the given type.
- class serpyco.SerializerMixin
Base class that provides load/dump, load_json/dump_json methods.
- dump(validate=False)
Dump the object to a dict.
- Return type:
Dict
[str
,Any
]
- dump_json(validate=False)
Dump the object to a JSON string.
- Return type:
str
- classmethod load(data, validate=True)
Load the given dict an return a new object.
- Return type:
TypeVar
(T
, bound= SerializerMixin)
- classmethod load_json(json_string, validate=True)
Load the given JSON string an return a new object.
- Return type:
TypeVar
(T
, bound= SerializerMixin)
- classmethod serializer()
Serializer instance for this class.
- Return type:
- class serpyco.StringFormat(value)
Possible formats for a string field
- exception serpyco.ValidationError(msg, errors=None)
Raised when an error is found during validation of data.
- Parameters:
msg (
str
) – formatted exception message(s).errors (
Optional
[Dict
[str
,str
]]) – dictionary of error message(s) where the key
is the JSON path to the invalid data.
- serpyco.field(dict_key=None, ignore=False, getter=None, validator=None, cast_on_load=False, description=None, examples=None, allowed_values=None, **kwargs)
Convenience function to setup Serializer hints on dataclass fields. Call it at field declaration as you would do with
dataclasses.field()
. Additional parameters will be passed verbatim todataclasses.field()
.- Parameters:
dict_key (
Optional
[str
]) – key of the field in the dumped dictionary.ignore (
bool
) – if True, the field won’t be considered by Serpyco.getter (
Optional
[Callable
[[object
],Any
]]) – callable used to get values of this field when dumping. Must take one object argument.validator (
Optional
[Callable
[[Any
],None
]]) – callable used to perform custom validation of this field. Will be called with values of the field, shall raise ValidationError() if the value is not valid.cast_on_load (
bool
) – when true, dict values for this field are constructed from the field’s type.description (
Optional
[str
]) – a description for the field. Will be included in the generated JSON schema.examples (
Optional
[List
[str
]]) – a list of example usages for the field. Will be included in the generated JSON schema.allowed_values (
Optional
[List
[Any
]]) – if given only values in this list will be considered valid during validation.
- Return type:
Any
- serpyco.nested_field(only=None, exclude=None, type_encoders=None, load_as_type=None, dict_key=None, ignore=False, getter=None, validator=None, description=None, examples=None, **kwargs)
Convenience function to setup Serializer hints on nested dataclass fields. Call it at field declaration as you would do with
dataclasses.field()
. Additional parameters will be passed verbatim todataclasses.field()
.- Parameters:
only (
Optional
[List
[str
]]) – if present, only fields in this list will be serialized.exclude (
Optional
[List
[str
]]) – if present, fields in this list will not be serialized.dict_key (
Optional
[str
]) – key of the field in the dumped dictionary.ignore (
bool
) – if True, the field won’t be considered by Serpyco.getter (
Optional
[Callable
[[object
],Any
]]) – callable used to get values of this field. Must take one object argument.validator (
Optional
[Callable
[[Any
],None
]]) – callable used to perform custom validation of this field. Will be called with values of the field, shall raise ValidationError() if the value is not valid.description (
Optional
[str
]) – a description for the field. Will be included in the generated JSON schema.examples (
Optional
[List
[str
]]) – a list of example usages for the field. Will be included in the generated JSON schema.
- Return type:
Any
- serpyco.number_field(dict_key=None, ignore=False, getter=None, validator=None, cast_on_load=False, description=None, examples=None, allowed_values=None, minimum=None, maximum=None, **kwargs)
Convenience function to setup Serializer hints for a number (int/float) dataclass field. Call it at field declaration as you would do with
dataclasses.field()
. Additional parameters will be passed verbatim todataclasses.field()
.- Parameters:
dict_key (
Optional
[str
]) – key of the field in the dumped dictionary.ignore (
bool
) – if True, this field won’t be considered by Serpyco.getter (
Optional
[Callable
[[object
],Any
]]) – callable used to get values of this field when dumping. Must take one object argument.validator (
Optional
[Callable
[[Any
],None
]]) – callable used to perform custom validation of this field. Will be called with values of the field, shall raise ValidationError() if the value is not valid.cast_on_load (
bool
) – when true, dict values for this field are constructed from the field’s type.description (
Optional
[str
]) – a description for the field. Will be included in the generated JSON schema.examples (
Optional
[List
[str
]]) – a list of example usages for the field. Will be included in the generated JSON schema.minimum (
Optional
[int
]) – minimum allowed value (inclusive).maximum (
Optional
[int
]) – maximum allowed value (inclusive).
- Return type:
Any
- serpyco.post_dump(method)
This decorator can be applied to a callable taking one dictionary and should return another dictionary. The method will then be called with each dictionary output by Serializer.dump or Serializer.dump_json after dumping them. :param: method method to call after dumping
- Return type:
Callable
[[Dict
[str
,Any
]],Dict
[str
,Any
]]
- serpyco.post_load(method)
This decorator can be applied to a callable taking one data class object and should return an object. The method will then be called with each object output by Serializer.load or Serializer.load_json before returning them. :param: method method to call after loading.
- Return type:
Callable
[[object
],object
]
- serpyco.pre_dump(method)
This decorator can be applied to a callable taking one object and should return an object of the dataclass it is declared in. The method will then be called with each object given to Serializer.dump or Serializer.dump_json before dumping them. :param: method method to call before dumping
- Return type:
Callable
[[object
],object
]
- serpyco.pre_load(method)
This decorator can be applied to a callable taking one dictionary and should return another dictionary. The method will then be called with each dictionary given to Serializer.load or Serializer.load before loading them in dataclass objects. :param: method method to call before loading
- Return type:
Callable
[[Dict
[str
,Any
]],Dict
[str
,Any
]]
- serpyco.string_field(dict_key=None, ignore=False, getter=None, validator=None, cast_on_load=False, description=None, examples=None, allowed_values=None, format_=None, pattern=None, min_length=None, max_length=None, **kwargs)
Convenience function to setup Serializer hints for a str dataclass field. Call it at field declaration as you would do with
dataclasses.field()
. Additional parameters will be passed verbatim todataclasses.field()
.- Parameters:
dict_key (
Optional
[str
]) – key of the field in the dumped dictionary.ignore (
bool
) – if True, this field won’t be considered by Serpyco.getter (
Optional
[Callable
[[object
],Any
]]) – callable used to get values of this field when dumping. Must take one object argument.validator (
Optional
[Callable
[[Any
],None
]]) – callable used to perform custom validation of this field. Will be called with values of the field, shall raise ValidationError() if the value is not valid.cast_on_load (
bool
) – when true, dict values for this field are constructed from the field’s type.description (
Optional
[str
]) – a description for the field. Will be included in the generated JSON schema.examples (
Optional
[List
[str
]]) – a list of example usages for the field. Will be included in the generated JSON schema.format – additional semantic validation for strings. Currently only used to better document the JSON schema, if you need special validation for a string, use a validator callable.
pattern (
Optional
[str
]) – restricts the strings of this field to the given regular expression.min_length (
Optional
[int
]) – minimum string length.max_length (
Optional
[int
]) – maximum string length.
- Return type:
Any