使用jsonschema加载和验证配置

schema-config的Python项目详细描述


架构配置

PyPIGitLabPyPI - ImplementationPyPI - Python VersionPyPI - WheelPyPI - Status

安装

至少需要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类类似于更简单的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中打开问题

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java JList侦听器找不到符号   多点触摸跨平台java应用程序(Windows、Mac和Linux(Ubuntu)(可能是Android))   在UnitTest中找不到java类加载器资源   java当我尝试在Eclipse中运行我的minecraft mod时,我总是遇到这个错误,这是什么意思?   内部有一个同步块的静态方法,在java中阻止整个类?   不支持java操作:具有BillableStatus的费用在采购中应具有AccountBasedExpenseLineDetail行的CustomerRef   java运行时常量池GC集合   java无法解析配置“:app:\u debugApk”的所有依赖项。找不到名为“default”的配置   在GCP计算引擎中托管Neo4j的java   java如何从BroadcastReceiver更新片段选项卡?   线程“main”组织中的java异常。冬眠注释异常:@org。冬眠注释。表引用未知表:ProductForPractice   在Java/Groovy中嵌入处理   java Android REST教程/示例项目   java我可以在同一测试中在一个模拟器上启动应用程序,在另一个模拟器上启动移动浏览器吗?   java如何更改通知横幅的方向?   安卓 Java帮助实现Firebase授权   if else之后的rs.next()中出现java错误?