Package: weelib
weelib(experimental)Library of additional functions forweepyframework.InstallationInstallation will not work - library  has not been released, yet.If you want to try functionality just clone git repo.Run installation command (requires python>=3.10):$pipinstallweelibUsingImport library and use its functionsimportweelibFunctionalityValidatorThis functionality provides data validation forlists,dicts and with extended class also decorator for validation requestsHTTP BODY.Simply inheritValidatorclass orRequestValidatorclass depending on what type validation you need.Create class variables usinRulepattern to create indivitual validation rules.
When you want validate input simply create instance of your class or (with RequestValidator) use class instance as decorator.Validatormethods and properties:__init__(self, data=None, exact_match) - class constructor accepts optionaldataparameter for automatic validation andexact_matchparameter specifying whether the data can contain keys validator doesn't contain__call__(self, data) - validate data (called automatically whendataparameter passed into__init__) - returns tuple (status, error<None | ValidationError | str>, key<str | None>)_init_validation_result- saved return_value from__call__when data passed to__init__directly
ValidationError contents:RequestValidatormethods and properties:__init__(self, exact_match) - decorator constructor -exact_matchparameter is same as inValidatorclass__call__(self, req, resp, *args, **kwargs) - method provides wrapper request data parsing - providesdataparameter with class instance value to decorated function_init_validation_result- saved return_value from__call__when data passed to__init__directlyRuleconstructor parameters:data_type- pythontypethat testing value must matchoptional- specifies whether rule is mandatory (boolean, default=False)min- specifies min value for typesintorfloat(int|float, optional)max- specifies max value for typesintorfloat(int|float, optional)length-  specifies length forstrorbytes(int, optional)min_length- specifies minimal length forstrorbytes(int, optional)max_length- specifies maximal length forstrorbytes(int, optional)regex- specifies regex to test forstrorbytes(Pattern, optional)check_method- specifiesfunction(orlambda) for more complex value check with one parameter (value) that returnsboolean(Callable, optional)ValidationErrorprovides enum of basic errors that may occur during validation -intended for extending to meet requirements of_validatewraps.ValidationErrorcontents:fromenumimportEnumclassValidatorError(Enum):MISSING_KEY="MISSING_KEY"INVALID_TYPE="INVALID_TYPE"INVALID_VALUE="INVALID_VALUE"NUMBER_NOT_IN_RANGE="NUMBER_NOT_IN_RANGE"LENGTH_NOT_IN_RANGE="LENGTH_NOT_IN_RANGE"INVALID_SCHEMA="INVALID_SCHEMA"General example:importrefromweelib.validatorimportValidator,Rulepassword="dude"classMyDataValidator(Validator):# for clarity is regex simplifiedemail=Rule(str,regex=re.compile(r".+\@.+\..+"))password=Rule(str,min_length=6)age=Rule(int,min=18)height=Rule(float,optional=True,min=1)# following method is optionaldef_validate(data):ifdata["password"]==password:returnTrue,None,""else:returnFalse,"INVALID_PASSWORD","password"person=MyDataValidator({"email":"test@test.com","password":"dude","age":25})print("email",person.email)print("age",person.age)print("height",person.heightor"not specified")POST data parser example:importrefromweepyimportASGI,Routefromweelib.validatorimportRequestValidator,Rulepassword="dude"classMyRequestDataValidator(RequestValidator):# for clarity is regex simplifiedemail=Rule(str,regex=re.compile(r".+\@.+\..+"))password=Rule(str,min_length=6)age=Rule(int,min=18)height=Rule(float,optional=True)# following method is optionaldef_validate(data):ifdata["password"]==password:returnTrue,None,""else:returnFalse,"INVALID_PASSWORD","password"application=ASGI(content_type="application/json",allow="*")@Route("/",methods=["POST"])@MyRequestDataValidator()asyncdefinfo(req,resp,data=None):return{"email":data.email,"password-length":len(data.password),"age":data.age,"height":data.heightor"not specified"}