在 Cerberus 中规范化嵌套字典
Normalize nested dict in Cerberus
我想在带有 Cerberus 规范化函数的嵌套字典中使用默认值。不幸的是它不起作用。 我有这样的代码:
from yaml import load, Loader
from cerberus import Validator
text_schema = """
server:
type: dict
required: True
schema:
host:
required: True
type: string
api:
type: dict
required: True
schema:
enabled:
type: boolean
required: True
default: True
"""
testyaml = """
server:
host: hostname
"""
schema = load(text_schema, Loader=Loader)
doc = load(testyaml, Loader=Loader)
v = Validator(schema, purge_unknown=True)
print(v.normalized(doc))
我最终得到:
{'server': {'host': 'hostname'}}
我希望有:
{'server': {'host': 'hostname', 'api': {'enabled': true}}}
这可能吗?
不太确定这是否合适,但只需向 api
键添加一个空的默认值即可。
text_schema = """
server:
type: dict
required: True
schema:
host:
required: True
type: string
api:
type: dict
required: True
default: {}
schema:
enabled:
type: boolean
required: True
default: True
"""
使用上面的模式,我得到:
{'server': {'host': 'hostname', 'api': {'enabled': True}}}