考虑以下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 员工 ID 是否与员工列表中的某个 id 值匹配?(参照完整性(
2( 如何验证员工列表中的每个 ID 是否唯一(即没有重复的员工 ID(?
我意识到我可以在验证和解析配置后在运行时执行此操作,如下@rafael建议。我想知道我是否可以使用 Cerberus 验证功能来做到这一点。
使用实现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 的架构,您可以像这样轻松检查您的两个条件。让文档成为您的 json 文档。
employee_ids = [employee['id'] for employee in doc['employee']]
ceo_employee_id = doc['ceo-employee-id']
1( 如何验证 CEO 员工 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')