我有这个YAML文件。我有Required和Optional密钥,还有可选的块,比如"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']['inux']['settings']['disk'],或['plugins']['http']['ssettings']['disk']是具有可选设置的'linux'或'http'变量字段。
Voluptuous文档对新手不友好:/
刚刚将YAML布局更改为
"
...
plugins:
linux:
disk:
critical: 90
warning: 80
exec:
exitcode: 0
http:
url: http://127.0.0.1
port: 8080
status: 200
...
"
并将其验证为
''' PLUGINS SETUP
'''
disk_settings = {
Optional('critical'): int,
Optional('warning'): int,
Optional('volume'): str,
}
exec_settings = {
Optional('exitcode'): int,
}
linux_settings = {
Optional('disk'): disk_settings,
Optional('exec'): exec_settings,
}
http_settings = {
Optional('url'): str,
Optional('port'): int,
Optional('status'): int,
}
plugins = {
Optional('linux'): linux_settings,
Optional('http'): http_settings,
}
''' CORE SCHEMA
'''
schema = Schema({
Required('project'): project,
Required('contact'): contact,
Optional('plugins'): plugins,
})
它正在工作:)