Package: commonkit
CommonKitInstallationpip install commonkitExamplesObfuscationfromcommonkit.utilsimportObfuscatorObfuscator.email("abcdqweqwe@test.com")# abcdq****@test.com'Obfuscator.obfuscate('my_super_confidential_secret')# 'my_super_confidential_s*****'Django rest framework related examples# models.pyfromdjango.dbimportmodelsclassHuman(models.Model):classLevel(models.IntegerChoices):BEGINNER=0INTERMEDIATE=1ADVANCED=2classMilitaryStatus(models.TextChoices):EXEMPTED="exempted","Exempted"SERVED="served","Served"POSTPONED="postponed","Postponed"name=models.CharField(max_length=128)level=models.IntegerField(choices=Level.choices)military_status=models.CharField(choices=MilitaryStatus.choices,max_length=128)# serializers.pyfromrest_frameworkimportserializersfromcommonkit.rest_framework.serializersimportEnumSerializerfromexample.coreimportmodelsclassHumanSerializer(serializers.ModelSerializer):level=EnumSerializer(enum=models.Human.Level)military_status=EnumSerializer(enum=models.Human.MilitaryStatus)classMeta:model=models.Humanfields=['id','level','military_status',]Example serialization# wherever.pyfromexample.core.serializersimportHumanSerializerfromexample.core.modelsimportHumanhuman=Human.objects.find(id=1)serializer=HumanSerializer(human)# level = BEGINNER, military_status = EXEMPTEDExample deserialization# wherever.pyfromexample.core.serializersimportHumanSerializerdata={"level":"BEGINNER","MILITARY_STATUS":"EXEMPTED",}instance=HumanSerializer(data=data)instance.is_valid()instance.save()Got some endpoints that accept files in table formats? got youAssuming Pandasimportpandasaspdfromcommonkit.rest_framework.pandasimportTableUploadField# or PandasTableUploadFieldfromrest_frameworkimportserializersclassMySerializer(serializers.ModelSerializer):file=TableUploadField()defcreate(self,validated_data):file:pd.DataFrame=validated_data['file']# do logic, don't do row based validation herereturnvalidated_data# optional methoddefvalidate_file_row(self,row,index,table_df):ifrow.iloc[0]=="X":row.iloc[0]="Y"# return new row, or None and changes won't be reflectedreturnrowAssuming Pola.rsimportpolarsasplfromcommonkit.rest_framework.polarsimportTableUploadField# or PolarsTableUploadFieldfromrest_frameworkimportserializersclassMySerializer(serializers.ModelSerializer):file=TableUploadField()defcreate(self,validated_data):file:pl.DataFrame=validated_data['file']# do logic, don't do row based validation herereturnvalidated_data# optional methoddefvalidate_file_row(self,row,index,table_df):# do polars logic, return new row or NonereturnrowTableUploadFieldiswrite_onlyTableUploadField is easily extended, use your own library if you wantfromcommonkit.rest_framework.serializersimportTableUploadFieldasBaseTableUploadFielddefread_csv(source):return...defread_excel(source):return...classTableUploadField(BaseTableUploadField):handlers={"csv":read_csv,"xlsx":read_excel,"xls":read_excel,"xlsm":read_excel,"xlsb":read_excel,"odf":read_excel,"ods":read_excel,"odt":read_excel,}defupdate_row(self,table_object:"YourLibraryDataFrame",index,new_row):"""how your library updates the row"""Supported formats are the keys in handlerscan_parse_csv="csv"infield.allowed_upload_formatsOrcan_parse_csv=field.is_allowed_format('obj')# FalseCustom kwargs for handlers in TableFieldUploadfromcommonkit.rest_framework.pandasimportPandasTableUploadFieldimportpandasaspdclassSerializer(...):pandas_file=PandasTableUploadField(handler_kwargs={# by format"xlsx":{# args for read_excel would be here"engine":"openpyxl"},# or by referencepd.read_csv:{"delimiter":"\t"}})The same logic applies to allTableUploadFieldsubclasses.commonkit provides easily methods for overriding most of the logic.If you want a field that does aggregation or something, overrideprocess_tableonTableUploadFieldObfuscationfromcommonkit.rest_framework.serializersimportObfuscatedCharField,ObfuscatedEmailField,ObfuscatedFieldMixinclassMySerializer(...):email=ObfuscatedEmailField()# in the API, it's obfuscatedname=ObfuscatedCharField()# same applies hereclassMyCustomObfuscatedApiKeyField(ObfuscatedFieldMixin,MyApiKeyField):passBetter error handlingREST_FRAMEWORK={"DEFAULT_RENDERER_CLASSES":["commonkit.rest_framework.renderers.JSONRenderer"]}This will change you response schema in case of errors toresponse={"field_errors":[],"non_field_errors":[]}ContributionsTo run the project locallypip install poetrypoetry installpoetry shellpre-commit installTo build the docsmake htmlTo run the testspytest .