根据架构验证dict
valedictor的Python项目详细描述
valedictory验证dicts中的数据。 设计用于API验证, 以及接收结构化json数据的其他情况 与关键值post-form数据相反。 它接受一个数据指令(可能是从json post请求获得的)。 并根据某些字段验证该数据。
验证器被定义为类。 声明验证器类上的字段。 一旦构造,验证程序实例是不可变的。
fromvaledictoryimportValidator,fields,InvalidDataExceptionclassPersonValidator(Validator):name=fields.CharField()height=fields.IntegerField()date_of_birth=fields.DateField()person_validator=PersonValidator()
可以检查python dict是否符合这个验证器。 dict可以来自json post请求或配置文件, 或任何其他需要验证和清理的外部数据源。 将返回已清除的数据。 验证器类将返回已清理数据的dict。 作为清理数据的一部分,每种字段类型都可以转换数据。 例如,DateField将转换数据 变成一个datetime.date实例。
input_data=json.loads(request.body)try:# cleaned_data will be a dict of cleaned, validated datacleaned_data=person_validator.clean(input_data)# Do something with the returned dataPerson.objects.create(**cleaned_data)exceptInvalidDataExceptionaserrors:# The data did not pass validationforpath,messageinerrors.flatten():# This will print something like 'name: This field is required'print("{0}: {1}".format('.'.join(path),message))
验证器可以嵌套,允许任意复杂度的DIST:
classArticleValidator(Validator):content=fields.CharField()published=fields.DateTimeField()author=fields.NestedValidator(PersonValidator())tags=fields.ListField(fields.CharField())# Some example data that would pass validation:data={"content":"An interesting article","published":"2018-06-13T1:44:00+10:00","author":{"name":"Alex Smith","height":175,"date_of_birth":"1990-03-26",},"tags":["humour","interesting","clickbait"],}
Read the documentation for more information。