python的配置模块,其中配置结构在python中单独定义,并具有完全的自动完成支持。
structured-config的Python项目详细描述
python的一个配置模块,其中配置结构是 用python定义。
有许多不同的模块和格式可用于创建 python项目中的配置文件。
不过,我过去使用过的所有方法都有一个主要的共同局限性; 不是用python编写的配置元素的主要定义, 或者它是用python dict之类的语言写的,在这里你没有特别了解 对元件进行良好的静态检查。
我个人喜欢在pycharm这样的智能ide中进行python开发 我可以充分利用检查和自动完成。如果配置为 但不是用python编写的,我不需要这样做。
如果您想要对配置文件进行任何类型的自省,那么您最终会得到一些 一种包含所有配置元素的配置文件的python解析器 在默认模板和某种镜像类中重复。
本模块旨在消除这一限制。
基本用法
现在,项目中的config.py文件可以类似于
from structured_config import ConfigFile, Structure class Config(Structure): class server(Structure): url = 'https:www.example.com' username = '<user>' password = '<password>' # Max number of tcp connections at any one time concurrent_connections = 32 # Local service port service_port = 45080 config = Config('/path/to/config.yaml')
项目中的任何其他模块都可以简单地
from config import config import requests from requests.auth import HTTPBasicAuth r = requests.get(config.server.url, auth=HTTPBasicAuth(config.server.username, config.server.password))
等等。你的ide应该给你所有这些元素的完整自动完成,因为它知道你的配置是 具有普通静态属性的普通类。
如果要在代码中更改这些配置项,只需设置属性即可
from config import config config.concurrent_connections = 64
就这样。在config()实例化中指向的yaml文件中将配置写入磁盘
当然,可以在磁盘上手动更改yaml文件。在这个阶段需要 重新启动应用程序以重新加载文件
!config server: !server password: <password> url: https:www.example.com username: <user> concurrent_connections: 32 service_port: 45080
元素列表
如果您想要一个稍微复杂一点的配置文件和一个元素列表,也可以对其进行处理
import structured_config from structured_config import Structure, ConfigFile # Pre-define the object we want to store a list of. class Map(Structure): remote_path = None local_path = None # Default configuration for the application class Config(Structure): class server(Structure): url = 'https:www.example.com' username = '<user>' password = '<password>' mapping = [ Map( remote_path="/test/", local_path="~/test/" ), Map( remote_path="/one/", local_path="~/two/" ), Map( remote_path="/two/", local_path="~/one/" ) ] config = Config('config.yaml')
您的主代码可以通过所有正常方式访问列表中的地图项。 如果将()个新的附加到列表中或将()个旧的附加到列表中,则 配置会自动将它们写入磁盘。对于编辑 添加到列表中的任何映射对象中的属性。
格式转换
如果您希望强制执行某些属性的类型,我们也将介绍这些属性
from structured_config import ConfigFile, Structure, TypedField, IntField class config(Structure): concurrent_connections = IntField(32) path = TypedField('$HOME', os.path.expandvars) config = Config('config.yaml')
- 当前可用的类型字段包括:
- intfield:转换为int()
- floatField:转换为float()
- strfield:转换为str()
- pathfield:转换为pathlib.path()
通过使用typefield(value,converter函数)可以根据需要创建其他文件 或者按照上面的方法对typefield进行子类化。
无论何时设置配置属性,它都将通过验证 功能优先。原始(未转换)值将保存到磁盘。
get在config object s属性中返回转换后的值,而不是field对象。
配置文件位置
实例化配置对象时,需要传入yaml文件名。
如果提供了绝对路径,则将逐字使用该路径。
假设相对路径存储在用于配置的标准系统位置中 文件,由appdirs处理。
- 在这种情况下,还应提供projects appname以创建文件夹
配置文件将存储在
config = Config('config.yaml', 'ExampleApp')