Package: cats-serialization
Cats SerializationIntroductionIt is a simple, extensible and functional serializer for objects.
The goal of the project is to provide a developer with a simple tool for developing REST applications... and not only =)More information inwikiGitrepoBuildInstall requirementssudo apt install python3-build, python3.11-venv, twineClone repogit clone http://git.dev-store.ru/Clu/cats-serialization-10
cd cats-serialization-10Try in project directorypython3 -m buildtwine upload dist/*Installationpip install cats-serializationMain FeaturesMulti style notationSerialization and deserializationValidation and logical operation with sameFull-object validation possibilityUnion types supportingCorrection values (by validators)Multi style notationclassBox(BaseSerializer):annotation:strfield=Field()defvirtual(self,data):returndata.do_smth(),custom_name# custom_name if neededSupport for union operationclassAddress(BaseSerializer):star:strplanet:strmoon:str|Undefined# like not requiredclassBox(BaseSerializer):address:str|Address# can be string or object# It`s ok for:# { address: 'Sun, Mars' }# { address: { star: 'Sun', planet: 'Mars' } }it works for fields notationclassBox(BaseSerialiser):# address is str or objectaddress=Field(is_type=str)|ObjectField(Address)Logical operation with validatorsone_field=Field(validator=IsType(int)|IsType(str))two_field=Field(validator=IsType(int)&IsRequired())Instance based serializerclassBox(Serialiser):passbox=Box()# New instanceprint(box.serialize(data))DeserializationclassGoods:passclassUnpack(Deserializer):passunpack=Unpack()goods=unpack.create(data,prototype=Goods)Correction values in passingclassIsName(BaseValidator):defvalidate(self,value,*args):iftype(value)isnotstr:raiseValidationError('It is not the name')returnvalue.strip()# safe correctionclassBox(BaseSerializer):# name will be corrected if type check will be passedname=Field(validator=IsName())UsesClass-based schemeIf you need to create class based serializer, it will just inherit onBaseSerializerclassclassMyScheme(BaseSerializer):passSerialization# Call serialize(...) from class MyScheme instantlysome_dict=MyScheme.serialize(some_data)Instance-based serialisationIt helps if it really neededclassMyScheme(Serializer):def__init__(self):passSerialization# At first, create instancescheme=MyScheme()# Now, you can call serialise(...)some_dict=scheme.serialize(some_data)Common FieldsAnnotationsIf you uses annotations, all field will be had type-check validationclassMyScheme(BaseSerializer):any:Any# Any fieldstring:str# Primitive fields with type validationnot_required:str|Undefined# Not required fieldblank:str|None# Can be blank fieldinteger:int|str|bool# Union fieldslist:list[str]# Generic listdefaults:str='Hello!'# Field with default valueitem:ItemScheme# Other serializeritems:list[ItemScheme]# List of other serializerFieldsclassMyScheme(BaseSerializer):field=Field()# Simple fielditem=ObjectField(ItemScheme)# Other serializeritems=IterableField(ItemScheme)# List of other serializerrequired=Field(is_required=True)# Any required fieldtyped=Field(is_type=str)# Required with type check# With validatorvalidated=Field(validator=IsStrong()&IsRequired())MethodsclassMyScheme(BaseSerializer):@classmethoddefvirtual(cls,data):returndata.sub_field,'override_name_if_needed'# it works, but be carefuldefvirtual_self(self,data):returndata.sub_field,'override_name_if_needed'Base Fields inheritclassMyField(BaseField):def__init__(self,**kwargs):super().__init__(**kwargs)Validation inheritGeneric validator has pattern:classMyValidator(BaseValidator):defvalidate(self,value,*args):ifsmth_wrong(value):raiseValidationError('Message')You can make full-object validator. For example, it needs if one field will depend on another.classMyValidator(BaseValidator):defvalidate(self,value,key,data):# use key and dataifdata.id==value:# it`s just exampleraiseValidationError('Message')