如果yaml文件有效,
yaml.safe_load()
方法会将文件转换为字典(在代码中用变量CONFIG
表示)。
第一次验证后,应该检查每个键以查看类型是否匹配。
from schema import Use, Schema, SchemaError
import yaml
config_schema = Schema(
{
"pipeline": Use(
str,
error="Unsupported pipeline name. A string input is expected"
),
"retry_parameters": Use(
int,
error="Unsupported retry strategy. An integer input is expected"
)
},
error="A yaml file is expected"
)
CONFIG = """
pipeline: 1
retry_parameters: 'pipe_1'
"""
configuration = yaml.safe_load(CONFIG)
try:
config_schema.validate(configuration)
print("Configuration is valid.")
except SchemaError as se:
for error in se.errors:
if error:
print(error)
在上面的示例中,它引发并打印三个错误。
A yaml file is expected
A yaml file is expected
Unsupported retry strategy. A integer input is expected
但在那种情况下,我期待以下结果:
Unsupported pipeline name. A string input is expected
Unsupported retry strategy. A integer input is expected
如何检查文件是否具有有效的 yaml 格式,然后检查每个键是否具有预期的类型?
使用库架构时出现问题。
首先,在Use中,参数指示值必须转换成的数据类型。由于 1 很容易转换为 '1',因此您不会收到第一条错误消息。因此,'pipe_1'无法转换为int,并且出现此异常。要解决此问题,请将 Use 更改为 And。
其次,由于该块是try/exept,所以第一个异常被捕获,所以第二个错误不会显示。前两个错误可能是由 Schema 类的第一个参数(字典)中的任何错误引起的。要输出所有错误,我认为有必要逐行检查并保存错误。