Python的智能配置
pyfiguration的Python项目详细描述
变形
pyconfiguration是Python的一个配置工具。它允许您从代码内部定义要使用的配置。pyconfiguration命令行工具可以帮助您检查哪些配置可用,允许的值是什么,并帮助检查特定脚本的配置文件的有效性。在
基本用途
在代码中,您可以定义哪些配置可用。这个例子创建了一个简单的Flask服务器。服务器启动的端口取决于配置。在
""" script.py"""frompyfigurationimportconffromflaskimportFlask@conf.addIntField(field="server.port",description="The port on which the server will start",default=8000,minValue=80,maxValue=9999,)defstartServer():app=Flask(__name__)port=conf["server"]["port"]print(f"Starting on port {port}")app.run(port=port)if__name__=="__main__":startServer()
可以使用pyconfiguration命令行工具检查此模块/脚本:
^{pr2}$这告诉您服务器端口是8000,它应该是一个介于80和9999之间的整数。运行脚本(python script.py
)将在默认端口上启动服务器。允许创建配置文件以覆盖默认值:
# config.yamlserver:port:5000
现在我们可以再次启动脚本,指向配置文件以使用它:
$ python script.py --config ./config.yaml Starting on port 5000 * Serving Flask app "script" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
成功!脚本使用了我们在config.yaml
文件中定义的配置。可以使用多个配置文件,并且都是YAML
和JSON
格式。请注意,如果存在重复项,这些键将被覆盖。这是一个有用的特性,您可以使用它来设置defaults.yaml
中的默认值,然后使用deployment.yaml
中的特定于部署的设置进行覆盖。也可以引用完整的文件夹。pyconfiguration将读取文件夹中的所有文件。对于完整的示例,请签出此存储库的./examples
文件夹。在
如果有配置文件和脚本,还可以使用pyconfiguration命令行检查配置文件是否有错误。映像此配置文件:
# config_with_warnings.yamlserver:port:500.0not_needed_key:some random value
显然我们在这里犯了两个错误:1:端口是一个浮点,2:有一个键没有被我们的脚本使用。让我们使用命令行工具来调查。在
$ pyfiguration inspect config -s script.py -c config_with_warnings.yaml -------- Errors-------- ✗ Value '500.0' is not of the correct type. The allowed data type is: int---------- Warnings---------- ! Key 'server.not_needed_key' doesn't exist in the definition and is not used in the module.
- 项目
标签: