基于yaml文件的配置解析器,支持变量、覆盖和层次结构
configcrunch的Python项目详细描述
configcrunch是一个python库,用于读取基于yaml的配置文件 同时也提供了一些非常强大的功能。
configcrunch与python 3.6及更高版本兼容。
通过pip安装:pip install configcrunch
功能:
- 从yaml文件读取配置文件。
- 定义可以通过模式验证的各种类型的配置文件。
- 配置文件的类型被定义为单独的python类。
- 文档可以配置为包含任何类型的子文档。
- 文档可以包含基于Jinja2的变量,这些变量可以 引用同一文档或父文档中的任何其他字段。
- 表示文档类型的类可以包含可以使用的方法 在配置文件中。
- 文档可以引用其他文件中的文档。configcrunch将它们合并在一起。 您可以决定参考文档的查找位置。
- 通过使用默认的python dict,也可以在不使用yaml文件的情况下创建配置对象。
- 所有功能都是可选的。
使用人:
- Riptide
- (你的项目在这里!打开一个问题。)
默认情况下,configcrunch使用schema来验证模式。 但您也可以使用自己的验证逻辑!
示例
这是一个使用上述大多数特性的示例,使用两种文档类型。
# doc1.yml - Type: oneone:name:Documentnumber:1sub:# Sub-document of type "two"$ref:/doc2two_field:"{{parent().method()}}"
# <lookup path>/doc2.yml - Type: twotwo:name:Doc 2number:2two_field:This is overridden
# classes.pyfromschemaimportSchema,OptionalfromconfigcrunchimportYamlConfigDocument,DocReference,load_subdocument,variable_helperclassOne(YamlConfigDocument):@classmethoddefheader(cls)->str:return"one"defschema(self)->Schema:returnSchema({Optional('$ref'):str,# reference to other One documents'name':str,'number':int,Optional('sub'):DocReference(Two)})defresolve_and_merge_references(self,lookup_paths):super().resolve_and_merge_references(lookup_paths)if"sub"inself:self["sub"]=load_subdocument(self["sub"],self,Two,lookup_paths)returnself@variable_helperdefmethod(self):return"I will return something"classTwo(YamlConfigDocument):@classmethoddefheader(cls)->str:return"two"defschema(self)->Schema:returnSchema({Optional('$ref'):str,# reference to other Two documents'name':str,'number':int,'two_field':str})
然后可以通过python读取文档“one.yml”:
>>> import yaml >>> from classes import One >>> doc = One.from_yaml('./doc1.yml') >>> doc.resolve_and_merge_references(['<lookup path>']) >>> doc.process_vars() >>> print(yaml.dump(doc.to_dict(), default_flow_style=False)) one: name: Document number: 1 sub: name: Doc 2 number: 2 two_field: I will return something
测试
在configcrunch.tests包中有验收测试。单元测试是在制品。
要运行测试,请参见run_tests.sh。
文档
完整的文档可以在Read the Docs(或docs目录)中找到。