【Python】validator进行数据校验


https://pypi.org/project/validator.py/

校验参数必要性

from validator import Required, In, InstanceOf, Length, validate, Range

 

rules = {

  # 1、Required 必要

  # 2、长度1-255

  # 3、类型string 

  'name': [Required, Length(1, 255), InstanceOf(str)]

}

data = {'name': ''}

chk = validate(rules, data)

print(chk)

# ValidationResult(valid=False, errors={'a': ['must be between 1 and 255  elements in Length']})

选填

# 非 Required 即可选

rules = {

  'name': [Length(1, 255), InstanceOf(str)],

  'user_id': [Length(11), InstanceOf(int)],

}