我需要解析很多yml文件。我有类似的例子,在某些情况下存在一个值,因此我需要更改另一个规则的正则表达式。我找不到正确验证它的方法
yaml1:
email: [email protected]
yaml2:
email: [email protected]
contract_type: external
模式:
schema = {
'email': {
'required': True,
'type': 'string',
'regex': '^([a-zA-Z0-9_\-\.]+)@company\.com$'
}
cerberus
包支持“开箱即用”的复合验证。validation-success
,validation-fail
或validation-skipped
aadocuments = []
aadocuments.append(yaml.safe_load('''
person_fname: homer
person_lname: himpson
person_age: 33
prize_caption: free beer for life
prize_email: [email protected]
prize_category: alchohol
'''))
aadocuments.append(yaml.safe_load('''
person_fname: helen
person_lname: himpson
person_age: 16
prize_caption: free ammo for life
prize_email: [email protected]
prize_category: firearms
'''))
Sample validation rule
- rule_caption: check-underage-minor
rule_vpath: '[@]|[? @.person_age < `18`]'
validation_schema:
prize_category:
type: string
allowed: ['pets','toys','candy']
prize_email:
type: string
regex: '[\w]+@.*'
person_age
小于18,那么:
断言prize_category
字段存在
断言prize_category
字段是字符串类型
断言prize_category
的价值是pets
或toys
或candy
断言prize_email
字段存在,类型为字符串
断言prize_email
字段匹配特定的正则表达式helen himpson
的结果将是validation-fail
。
check-underage-minor
验证规则触发,因为person_age == 16
prize_cateogry
的值为firearms
,这是不允许的,因此验证失败rule_vpath
,当且仅当person_age
存在且小于18时,它告诉系统触发此特定规则。这会增加对jmespath的依赖性。