我有这个 YAML 文件。我有必需和可选键,还有可选块,如“linux”、“http”等。
---
project:
name: lolproj
url: http://wiki.tld/lolproj
contact:
name: FooBar
email: foobar@gmail.com
plugins:
linux:
settings:
disk:
critical: 90
warning: 80
http:
...
我正在以这种方式加载和验证它:
from voluptuous import *
def main():
with open('mytiny.yaml', 'r') as f:
mon = yaml.safe_load(f)
project = {
Required('name'): All(str, Length(min=5), msg="Must be a string!"),
Required('url'): All(str, Length(min=5))
}
contact = {
Required('name'): All(str, Length(min=5)),
Required('email'): All(str, Length(min=5)),
}
disk_settings = {
'warning': int,
'critical': int,
}
plugins = ['linux','http','mysql']
schema = Schema({
Required('project'): project,
Required('contact'): contact,
Optional('plugins'): plugins,
Optional('settings'): {
Optional('disk'): disk_settings,
}
})
但我收到此错误:
Traceback (most recent call last):
File "./readmon.py", line 143, in <module>
main()
File "./readmon.py", line 43, in main
schema(mon)
File "/usr/local/lib/python2.7/site-packages/voluptuous.py", line 207, in __call__
return self._compiled([], data)
File "/usr/local/lib/python2.7/site-packages/voluptuous.py", line 386, in validate_dict
return base_validate(path, iteritems(data), out)
File "/usr/local/lib/python2.7/site-packages/voluptuous.py", line 287, in validate_mapping
raise MultipleInvalid(errors)
voluptuous.MultipleInvalid: expected a list for dictionary value @ data['plugins']
所以,看起来我在做一些非常糟糕的事情。对此有任何提示吗?问题是,我想要一个类似的东西:
['plugins']['linux']['settings']['disk'],或 ['plugins']['http']['settings']['disk'] 是 'linux' 或'http ' 具有可选设置的变量字段。
华丽的文档对新手不友好:/