使用jsonschema加载和验证配置
schema-config的Python项目详细描述
架构配置
安装
至少需要cpython/pypy 3.6
pip3 install schema-config~=[version]
警告:在此早期版本(0.x.y)中,次要版本可能会引入重大的中断更改!
用法
加载配置
frompkg_resourcesimportresource_stringfromosimportenvironfromschema_configimportConfiguratorschema:bytes=resource_string(__name__,"config.schema.json")factory:Configurator=Configurator.from_string(schema)# The order is important, the first file will be loadedif"CONFIG"inenviron:# loads the configuration from a yaml file (typings come from YAML)factory.add_file(environ["CONFIG"])else:# Search for your programm's configurationsfactory.add_file("/etc/programm/config.yaml")factory.add_file("./programm.yaml")# Get your configuration objectcfg=factory.load_config()
指定配置架构
架构配置是使用jsonschema配置的。
可能的模式是:
{"$schema":"http://json-schema.org/draft-04/schema","properties":{"database":{"type":"object","properties":{"host":{"type":"string"},"port":{"type":"number"},"password":{"type":"string"}},"required":["host"]}},"required":["database"]}
配置程序
通过上面的示例,用户可以如下配置程序:
/etc/program/config.yaml
:
database:host:"example.com"port:$json{DB_PORT}password:$string{DB_PASSWORD}
使用环境变量(当前需要引号):
DB_PORT="9999"DB_PASSWORD="test"
两者都将合并到类似于:
的Configuration
对象中。
{"database":{"host":"example.com","port":9999,"password":"test"}}
Configurator
类
创建
从文件中
factory=Configurator.from_file("<file name>")
从字符串
factory=Configurator.from_string("<json schema as a string>")
从听写中
factory=Configurator(json_schema_as_a_dict)
添加文件
factory.add_file("<file path>")
警告:顺序很重要!第一个将加载
获取配置
cfg=factory.load_config()# type: Configuration
Configuration
类
Configuration
类Configuration
类类似于更简单的dict
。
获取项目
使用KeyError
如果不可用
database=cfg["database"]host=cfg["database.host"]
默认情况下:
host=cfg.get("database.host","localhost")password=cfg.get("database.password")# Default: None
检查项目
cfg.has("database.host")"database.host"incfg
设置项目
cfg["database"]={"host":"example.com"}cfg["database.host"]="example.com"
其他有用的能力
创建新配置
cfg=Configuration(some_dict)
从中获取一个指令
dict_cfg=cfg.raw
问题和建议
如果您有任何问题、建议、许可问题等,请在the gitlab repo中打开问题