0

我有这个 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 ' 具有可选设置的变量字段。

华丽的文档对新手不友好:/

4

1 回答 1

1

刚刚将 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,
})

它正在工作:)

于 2013-08-13T14:53:34.373 回答