To get rid of code snippet like these (... cumbersome and tedious validation)
defdo_something(params):
val_a_must_int=params.get('a', 0)
val_b_must_be_non_empty_list=params.get('b', [])
# if key c presents, value c must be a date string between '2000-01-01' to '2020-01-01'val_c_might_be_none=params.get('c', None)
# check typeiftype(val_a_must_int) !=int:
raiseXXX# check type & valueiftype(val_b_must_list) !=listorlen(val_b_must_be_non_empty_list) ==0:
raiseXXX# if value exists, check its valueifval_c_might_be_noneisnotNone:
date_c=datetime.strptime(val_c_might_be_present, '%Y-%m-%d')
date_20000101=datetime.date(2000, 1, 1)
date_20200101=datetime.date(2020, 1, 1)
ifnot (date_20000101<=date_c<=date_20200101):
raiseXXX
...
# do something actually
Installation
Basic usage:
pip install data-spec-validator
Advance usage (decorator)
The decorator function dsv depends on Django & djangorestframework.
pip install data-spec-validator[decorator]
Quick Example
Do validate_data_spec directly wherever you like (see test_spect.py for more)
Decorate another method with dsv_request_meta can help you validate the META in request header.
Register Custom Spec Check & Validator
Define custom CHECK constant (gt_check in this case) and write custom Validator(GreaterThanValidator in this case)
gt_check='gt_check'fromdata_spec_validator.spec.definesimportBaseValidatorclassGreaterThanValidator(BaseValidator):
name=gt_check@staticmethoddefvalidate(value, extra, data):
criteria=extra.get(GreaterThanValidator.name)
returnvalue>criteria, ValueError(f'{value} is not greater than {criteria}')
Register custom check & validator into data_spec_validator
2 modes (Default v.s. Vague), can be switched by calling reset_msg_level(vague=True)
# In default mode, any exception happens, there will be a reason in the message"field: XXX, reason: '3' is not a integer"# In vague mode, any exception happens, a general message is shown"field: XXX not well-formatted"