配置管理器
kaptan的Python项目详细描述
配置分析器。
安装
$ pip install kaptan
在FreeBSD、Debian、Arch Linux和Slackware上也可以作为一个包提供。
用法
支持的处理程序
- dict
- json
- 山药
- .ini
- python文件
默认(dict)处理程序
config=kaptan.Kaptan()config.import_config({'environment':'DEV','redis_uri':'redis://localhost:6379/0','debug':False,'pagination':{'per_page':10,'limit':20,}})printconfig.get("pagination.limit")# output: 20
json处理程序
config=kaptan.Kaptan(handler="json")config.import_config('{"everything": 42}')printconfig.get("everything")# output: 42
yaml处理程序
config=kaptan.Kaptan(handler="yaml")config.import_config(""" product: price: value: 12.65 currency_list: 1. TL 2. EURO """)printconfig.get("product.price.currency_list.0")# output: TL
或者您可以直接从文件名获取:
config.import_config("configuration.yaml")
.ini处理程序
配置ini
[development]database_uri=mysql://root:123456@localhost/posts[production]database_uri=mysql://poor_user:poor_password@localhost/poor_posts
config=kaptan.Kaptan(handler="ini")config.import_config('config.ini')printconfig.get("production.database_uri")# output: mysql://poor_user:poor_password@localhost/poor_posts
文件处理程序
配置py
DATABASE='mysql://root:123456@localhost/posts'DEBUG=FalsePAGINATION={'per_page':10,'limit':20,}
config=kaptan.Kaptan(handler="file")config.import_config('config')printconfig.get("DEBUG")# output: False
导出配置
config=kaptan.Kaptan(handler="file")config.import_config({'environment':'DEV','redis_uri':'redis://localhost:6379/0','debug':False,'pagination':{'per_page':10,'limit':20,}})printconfig.export("yaml")
输出:
debug:falseenvironment:DEVpagination:{limit:20, per_page:10}redis_uri:redis://localhost:6379/0
print config.export("json")
输出未缩进的json。.export接受传入 json.dumps。
printconfig.export("json",indent=4)
输出:
{"environment":"DEV","debug":false,"pagination":{"per_page":10,"limit":20},"redis_uri":"redis://localhost:6379/0"}
config.export('yaml')还支持kwargs for pyyaml。
0.5.7版中的新功能:config.export('yaml', safe=True)将使用.safe_dump。
cli
导出(默认为json)
$echo"environment: DEV" > config.yaml $ kaptan config.yaml --export json > config.json $ cat config.json {"environment": "DEV"}
获取值
$ kaptan config.yaml --key environment DEV
指定处理程序
$ mv config.yaml config.settings $ kaptan config.settings:yaml --export json {"environment": "DEV"}
从stdin进行配置
$echo'{"source": "stdin"}'| kaptan - {"source": "stdin"} $echo'source: stdin'| kaptan -:yaml {"source": "stdin"}
合并配置
$echo"environment: PROD" > config.settings $echo'{"source": "stdin"}'| kaptan - config.json config.settings:yaml {"environment": "PROD", "source": "stdin"}
设置默认处理程序
$echo"source: stdin"| kaptan --handler yaml - config.settings {"environment": "PROD", "source": "stdin"}
使用yaml编写json
$ kaptan -:yaml -e json <type yaml here> <Ctrl + D> <get json here>
运行测试
使用py.test:
$ py.test