考虑以下Cerberus架构:
{
'employee': {
'type': 'list',
'schema': {
'type': 'dict',
'schema': {
'id': {'required': True, 'type': 'integer'},
'name': {'required': True, 'type': 'string'}
}
}
},
'ceo-employee-id': {'required': True, 'type': 'integer'}
}
1)如何验证ceo-employee-id是否与员工列表中的某个id值匹配? (参照完整性)
2)如何验证员工列表中的每个ID是唯一的(即没有重复的员工ID)?
我知道我可以在验证和解析配置之后在运行时执行此操作,如下面@rafael所建议的那样。我想知道我是否可以使用Cerberus验证功能。
您需要使用实现custom validator方法的check_with
,在这些方法中使用document
属性,并修改您的模式以包含以下内容:
from cerberus import Validator
class CustomValidator(Validator):
def _check_with_ceo_employee(self, field, value):
if value not in (x["id"] for x in self.document["employee"]):
self._error(field, "ID is missing in employee list.")
def _check_with_employee_id_uniqueness(self, field, value):
all_ids = [x["id"] for x in self.document["employee"]]
if len(all_ids) != len(set(all_ids)):
self._error(field, "Employee IDs are not unique.")
validator = CustomValidator({
'employee': {
'type': 'list',
'schema': {
'type': 'dict',
'schema': {
'id': {'required': True, 'type': 'integer'},
'name': {'required': True, 'type': 'string'}
},
},
'check_with': 'employee_id_uniqueness'
},
'ceo-employee-id': {'required': True, 'type': 'integer', 'check_with': 'ceo_employee'}
})
引用的文档包含此处使用的所有部件的提示。
(对于可能在示例中出现的任何缩进错误,我深表歉意。)
假设您已经验证了json的模式,您可以轻松地检查这两个条件。让doc成为你的json文档。
employee_ids = [employee['id'] for employee in doc['employee']]
ceo_employee_id = doc['ceo-employee-id']
1)如何验证ceo-employee-id是否与员工列表中的某个id值匹配? (参照完整性)
ceo_id_exists_in_employees = any([employee_id == ceo_employee_id for employee_id in employee_ids])
2)如何验证员工列表中的每个ID是唯一的(即没有重复的员工ID)?
employee_id_is_unique = len(set(employee_ids)) == len(employee_ids)
3)断言两个值都是True
if ceo_id_exists_in_employees and employee_id_is_unique:
print('passed')
else:
print('failed')