使用基于 YAML 的模式对 YAML 配置文件进行简单验证。
项目描述
背景
Phyles 是一组有点折衷的功能,它使实用程序(可以由配置文件控制的小程序)的实现更容易。它最初是大量样板文件,我会复制到我编写的几乎所有实用程序中。我最终决定将此代码合并到一个包中,并添加一些基于模式的配置文件验证并完整记录它。
特征
Phyles 提供对基于YAML的配置文件的支持以及验证配置文件的方法。Phyles 还提供了一些使实用程序更加用户友好的工具,包括自动生成的横幅、自动记录的配置模板以及从配置错误中正常恢复。
主页和存储库
phyles 主页是http://phyles.bravais.net,源代码维护在 github:https ://github.com/jcstroud/phyles 。
例子
phyles 提供的大约 90% 的便利可以用几行代码来概括。从教程中的示例实用程序 ( http://pythonhosted.org/phyles ):
1| spec = phyles.package_spec(phyles.Undefined, "barbecue",
| "schema", "barbecue-time.yml")
2| converters = {'celsius to farenheit':
| barbecue.celsius_to_farenheit}
3| setup = phyles.set_up(__program__, __version__,
| spec, converters)
4| phyles.run_main(main, setup['config'],
| catchall=barbecue.BarbecueError)
这几行从包内容中找到模式规范(第 1 行),解析命令行参数(第 3 行),验证配置文件(第 2 行和第 3 行),覆盖其中的配置设置(第 3 行),并运行主函数try-except 块中的实用程序的一部分,以确保在引发预期异常的情况下正常退出(第 4 行)。
Schema 在YAML中指定,简洁,希望直观。以下是教程中的示例:
!!omap
- dish :
- - vegetable kabobs
- smoked salmon
- brisket
- smoked salmon
- Dish to cook
- doneness :
- rare : 200
medium : 350
well-done : 500
- medium
- How much to cook the dish
- temperature :
- celsius to farenheit
- 105
- Cooking temperature in °C
- 105
- width :
- int
- 70
- width of report
- 70
如果用户使用--template(或-t)命令行选项运行该实用程序,Phyles 将自动为用户生成记录的示例配置文件。在本教程中,使用以下命令调用示例脚本 ( BBQ-time ):
barbecue_time -t
产生以下输出,这对上述模式有效:
%YAML 1.2
---
# Dish to cook
# One of: vegetable kabobs, smoked salmon, brisket
dish : smoked salmon
# How much to cook the dish
# One of: well-done, medium, rare
doneness : medium
# Cooking temperature in °C
temperature : 105
# width of report
width : 70
作为最后一个示例,此模式的另一个有效配置文件是:
dish : smoked salmon
doneness : medium
temperature : 107
width : 70