yamlcfgload 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- yamlcfgload-0.1.0/.gitignore +20 -0
- yamlcfgload-0.1.0/LICENSE +22 -0
- yamlcfgload-0.1.0/PKG-INFO +206 -0
- yamlcfgload-0.1.0/README.md +174 -0
- yamlcfgload-0.1.0/pyproject.toml +72 -0
- yamlcfgload-0.1.0/setup.cfg +4 -0
- yamlcfgload-0.1.0/src/cfgload/__init__.py +12 -0
- yamlcfgload-0.1.0/src/cfgload/config.py +207 -0
- yamlcfgload-0.1.0/src/cfgload/errors.py +48 -0
- yamlcfgload-0.1.0/src/cfgload/loaders.py +97 -0
- yamlcfgload-0.1.0/src/cfgload/matchers.py +40 -0
- yamlcfgload-0.1.0/src/cfgload/validators.py +73 -0
- yamlcfgload-0.1.0/src/yamlcfgload.egg-info/PKG-INFO +206 -0
- yamlcfgload-0.1.0/src/yamlcfgload.egg-info/SOURCES.txt +17 -0
- yamlcfgload-0.1.0/src/yamlcfgload.egg-info/dependency_links.txt +1 -0
- yamlcfgload-0.1.0/src/yamlcfgload.egg-info/requires.txt +10 -0
- yamlcfgload-0.1.0/src/yamlcfgload.egg-info/scm_file_list.json +14 -0
- yamlcfgload-0.1.0/src/yamlcfgload.egg-info/scm_version.json +8 -0
- yamlcfgload-0.1.0/src/yamlcfgload.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
*.pyo
|
|
2
|
+
*.pyc
|
|
3
|
+
*.swp
|
|
4
|
+
.DS_Store
|
|
5
|
+
*~
|
|
6
|
+
build/
|
|
7
|
+
dist/
|
|
8
|
+
forgery-py.sublime-project
|
|
9
|
+
forgery-py.sublime-workspace
|
|
10
|
+
docs/_build/
|
|
11
|
+
.idea/
|
|
12
|
+
tmp/
|
|
13
|
+
.coverage
|
|
14
|
+
TODO.rst
|
|
15
|
+
*.egg-info/
|
|
16
|
+
.mypy_cache/
|
|
17
|
+
.pytest_cache/
|
|
18
|
+
htmlcov/
|
|
19
|
+
__pycache__/
|
|
20
|
+
_version.py
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2016 Vitaly R. Samigullin
|
|
4
|
+
Copyright (c) 2026 wangxl8
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included
|
|
14
|
+
in all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: yamlcfgload
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Load YAML configs with environment variables interpolation
|
|
5
|
+
Author-email: wangxl8 <71364605@qq.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gitee.com/wangxinglong520/cfgload
|
|
8
|
+
Project-URL: Source code, https://gitee.com/wangxinglong520/cfgload
|
|
9
|
+
Project-URL: Issue tracker, https://gitee.com/wangxinglong520/cfgload/issues
|
|
10
|
+
Keywords: yaml,config,configuration,environment-variables,interpolation
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Information Technology
|
|
14
|
+
Classifier: Intended Audience :: System Administrators
|
|
15
|
+
Classifier: Operating System :: Unix
|
|
16
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
17
|
+
Classifier: Environment :: Console
|
|
18
|
+
Classifier: Environment :: MacOS X
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: Internet
|
|
21
|
+
Requires-Python: >=3.7
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: PyYAML<7,>=6
|
|
25
|
+
Provides-Extra: pydantic
|
|
26
|
+
Requires-Dist: pydantic>=0.28; extra == "pydantic"
|
|
27
|
+
Provides-Extra: marshmallow
|
|
28
|
+
Requires-Dist: marshmallow>=3; extra == "marshmallow"
|
|
29
|
+
Provides-Extra: trafaret
|
|
30
|
+
Requires-Dist: trafaret>=1.2.0; extra == "trafaret"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# yamlcfgload
|
|
34
|
+
|
|
35
|
+
从 YAML 文件加载配置,支持环境变量插值和可选的 schema 校验。
|
|
36
|
+
|
|
37
|
+
包名为 `yamlcfgload`,导入名为 `cfgload`。
|
|
38
|
+
|
|
39
|
+
## 特性
|
|
40
|
+
|
|
41
|
+
- 在 YAML 中用 `${VAR}` 引用环境变量,用 `${VAR:-default}` 指定默认值
|
|
42
|
+
- 基于 `yaml.SafeLoader`,不执行任意 Python 对象
|
|
43
|
+
- 可选的 schema 校验,支持 pydantic、marshmallow、trafaret
|
|
44
|
+
- `Config` 类:一次加载、全局访问,支持点号路径、列表下标、环境变量覆盖和取值缓存
|
|
45
|
+
|
|
46
|
+
## 安装
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install yamlcfgload
|
|
50
|
+
# 可选的校验器扩展
|
|
51
|
+
pip install "yamlcfgload[pydantic]"
|
|
52
|
+
pip install "yamlcfgload[marshmallow]"
|
|
53
|
+
pip install "yamlcfgload[trafaret]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
要求 Python 3.7+,核心依赖只有 PyYAML。
|
|
57
|
+
|
|
58
|
+
## 快速开始
|
|
59
|
+
|
|
60
|
+
### 1. 加载 YAML 并插值环境变量
|
|
61
|
+
|
|
62
|
+
`config.yaml`:
|
|
63
|
+
|
|
64
|
+
```yaml
|
|
65
|
+
database:
|
|
66
|
+
host: ${DB_HOST:-localhost}
|
|
67
|
+
port: 5432
|
|
68
|
+
user: ${DB_USER}
|
|
69
|
+
cache:
|
|
70
|
+
- host: 127.0.0.1
|
|
71
|
+
ttl: 60
|
|
72
|
+
debug: true
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from cfgload import YamlLoader
|
|
77
|
+
|
|
78
|
+
config = YamlLoader(path="config.yaml").load()
|
|
79
|
+
|
|
80
|
+
print(config["database"]["host"]) # 环境变量 DB_HOST 的值;未设置时为 localhost
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
环境变量未设置且没有默认值时,该项为 `None`:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
import os
|
|
87
|
+
from cfgload import YamlLoader
|
|
88
|
+
|
|
89
|
+
os.environ.pop("DB_USER", None)
|
|
90
|
+
print(YamlLoader(path="config.yaml").load()["database"]["user"]) # None
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### 2. 使用 Config 管理全局配置
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from cfgload import Config
|
|
97
|
+
|
|
98
|
+
Config.load_config("config.yaml", use_cache=True)
|
|
99
|
+
|
|
100
|
+
Config.get("database.host") # 点号路径取值
|
|
101
|
+
Config.get("database.port", 3306) # 不存在时返回默认值
|
|
102
|
+
Config.get("cache[0].ttl") # 列表下标
|
|
103
|
+
Config.get_int("database.port") # 转成 int,失败返回默认值
|
|
104
|
+
Config.get_bool("debug") # 识别 true/1/yes/on
|
|
105
|
+
Config.get_required("database.host") # 必须存在,否则抛出 ValueError
|
|
106
|
+
Config.get_config() # 整个配置字典的副本
|
|
107
|
+
Config.clear_cache() # 清除取值缓存
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`Config.get` 的取值顺序:
|
|
111
|
+
|
|
112
|
+
1. 环境变量:以参数路径本身作为环境变量名,例如 `Config.get("database.port")` 优先读取环境变量 `database.port`。环境变量的值始终是字符串,需要数字或布尔值时请使用 `get_int` / `get_bool`。
|
|
113
|
+
2. YAML 配置:按 `a.b.c` 或 `a[0].b` 形式的路径逐级查找。
|
|
114
|
+
3. 都不存在时返回 `default`(默认为 `None`)。
|
|
115
|
+
|
|
116
|
+
注意:
|
|
117
|
+
|
|
118
|
+
- `load_config` 只在第一次调用时真正读取文件,之后再调用会直接返回已加载的配置,传入新的路径也不会重新加载。
|
|
119
|
+
- 未调用 `load_config` 就调用 `get`,会抛出 `TypeError`。
|
|
120
|
+
- `use_cache=True` 时,`get` 的结果会按路径缓存(最多 512 项);配置变化后需要调用 `clear_cache()`。
|
|
121
|
+
|
|
122
|
+
### 3. 从字符串或流中加载
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from cfgload import YamlStreamLoader
|
|
126
|
+
|
|
127
|
+
config = YamlStreamLoader(stream="host: ${DB_HOST:-localhost}\n").load()
|
|
128
|
+
print(config["host"])
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### 4. Schema 校验
|
|
132
|
+
|
|
133
|
+
传入校验器和 schema 后,`load()` 返回校验后的数据,校验失败时抛出 `cfgload.errors.ValidationError`。
|
|
134
|
+
|
|
135
|
+
以 pydantic v2 为例:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from pydantic import BaseModel
|
|
139
|
+
from cfgload import YamlLoader, PydanticV2Validator
|
|
140
|
+
|
|
141
|
+
class Database(BaseModel):
|
|
142
|
+
host: str
|
|
143
|
+
port: int
|
|
144
|
+
|
|
145
|
+
class Settings(BaseModel):
|
|
146
|
+
database: Database
|
|
147
|
+
|
|
148
|
+
config = YamlLoader(
|
|
149
|
+
path="config.yaml",
|
|
150
|
+
validator=PydanticV2Validator,
|
|
151
|
+
schema=Settings,
|
|
152
|
+
).load()
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
可用的校验器:
|
|
156
|
+
|
|
157
|
+
| 校验器 | 扩展依赖 | 说明 |
|
|
158
|
+
| --- | --- | --- |
|
|
159
|
+
| `PydanticV2Validator` | `cfgload[pydantic]` | pydantic 2.x,返回 `model_dump()` 的结果 |
|
|
160
|
+
| `PydanticValidator` | `cfgload[pydantic]` | pydantic 1.x,返回 `dict()` 的结果 |
|
|
161
|
+
| `MarshmallowValidator` | `cfgload[marshmallow]` | marshmallow 3.x |
|
|
162
|
+
| `TrafaretValidator` | `cfgload[trafaret]` | trafaret |
|
|
163
|
+
|
|
164
|
+
也可以继承 `cfgload.validators.Validator` 实现自己的校验器,只需实现 `load(data, **params)` 方法。
|
|
165
|
+
|
|
166
|
+
## 环境变量插值规则
|
|
167
|
+
|
|
168
|
+
| 写法 | 含义 |
|
|
169
|
+
| --- | --- |
|
|
170
|
+
| `${VAR}` | 替换为环境变量 `VAR` 的值;未设置时为 `None` |
|
|
171
|
+
| `${VAR:-default}` | 未设置时使用 `default` |
|
|
172
|
+
|
|
173
|
+
- 只支持整个值被替换,即 `${...}` 必须位于值的开头。`prefix-${VAR}` 不会被替换,会原样保留。
|
|
174
|
+
- 环境变量名只允许字母、数字、下划线和 `$`。
|
|
175
|
+
- 变量未设置且没有默认值时得到 `None`,不是空字符串,也不报错。
|
|
176
|
+
|
|
177
|
+
## 异常
|
|
178
|
+
|
|
179
|
+
所有异常都定义在 `cfgload.errors` 中,基类为 `ConfigError`:
|
|
180
|
+
|
|
181
|
+
| 异常 | 触发场景 |
|
|
182
|
+
| --- | --- |
|
|
183
|
+
| `LoadingError` | 文件不存在或 YAML 解析失败 |
|
|
184
|
+
| `ValidationError` | schema 校验失败 |
|
|
185
|
+
|
|
186
|
+
原始异常保存在异常对象的 `origin` 属性中。
|
|
187
|
+
|
|
188
|
+
## 开发与发布
|
|
189
|
+
|
|
190
|
+
版本号由 git 标签生成(setuptools_scm),发布前先打标签,并保持工作区干净:
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
pip install --upgrade build twine
|
|
194
|
+
|
|
195
|
+
git tag v0.1.0
|
|
196
|
+
python -m build
|
|
197
|
+
|
|
198
|
+
twine check dist/*
|
|
199
|
+
twine upload dist/*
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
未打标签时构建出的版本号形如 `0.1.dev1`,PyPI 不接受这样的版本,无法上传。
|
|
203
|
+
|
|
204
|
+
## 许可证
|
|
205
|
+
|
|
206
|
+
MIT,见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# yamlcfgload
|
|
2
|
+
|
|
3
|
+
从 YAML 文件加载配置,支持环境变量插值和可选的 schema 校验。
|
|
4
|
+
|
|
5
|
+
包名为 `yamlcfgload`,导入名为 `cfgload`。
|
|
6
|
+
|
|
7
|
+
## 特性
|
|
8
|
+
|
|
9
|
+
- 在 YAML 中用 `${VAR}` 引用环境变量,用 `${VAR:-default}` 指定默认值
|
|
10
|
+
- 基于 `yaml.SafeLoader`,不执行任意 Python 对象
|
|
11
|
+
- 可选的 schema 校验,支持 pydantic、marshmallow、trafaret
|
|
12
|
+
- `Config` 类:一次加载、全局访问,支持点号路径、列表下标、环境变量覆盖和取值缓存
|
|
13
|
+
|
|
14
|
+
## 安装
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install yamlcfgload
|
|
18
|
+
# 可选的校验器扩展
|
|
19
|
+
pip install "yamlcfgload[pydantic]"
|
|
20
|
+
pip install "yamlcfgload[marshmallow]"
|
|
21
|
+
pip install "yamlcfgload[trafaret]"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
要求 Python 3.7+,核心依赖只有 PyYAML。
|
|
25
|
+
|
|
26
|
+
## 快速开始
|
|
27
|
+
|
|
28
|
+
### 1. 加载 YAML 并插值环境变量
|
|
29
|
+
|
|
30
|
+
`config.yaml`:
|
|
31
|
+
|
|
32
|
+
```yaml
|
|
33
|
+
database:
|
|
34
|
+
host: ${DB_HOST:-localhost}
|
|
35
|
+
port: 5432
|
|
36
|
+
user: ${DB_USER}
|
|
37
|
+
cache:
|
|
38
|
+
- host: 127.0.0.1
|
|
39
|
+
ttl: 60
|
|
40
|
+
debug: true
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from cfgload import YamlLoader
|
|
45
|
+
|
|
46
|
+
config = YamlLoader(path="config.yaml").load()
|
|
47
|
+
|
|
48
|
+
print(config["database"]["host"]) # 环境变量 DB_HOST 的值;未设置时为 localhost
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
环境变量未设置且没有默认值时,该项为 `None`:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import os
|
|
55
|
+
from cfgload import YamlLoader
|
|
56
|
+
|
|
57
|
+
os.environ.pop("DB_USER", None)
|
|
58
|
+
print(YamlLoader(path="config.yaml").load()["database"]["user"]) # None
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### 2. 使用 Config 管理全局配置
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from cfgload import Config
|
|
65
|
+
|
|
66
|
+
Config.load_config("config.yaml", use_cache=True)
|
|
67
|
+
|
|
68
|
+
Config.get("database.host") # 点号路径取值
|
|
69
|
+
Config.get("database.port", 3306) # 不存在时返回默认值
|
|
70
|
+
Config.get("cache[0].ttl") # 列表下标
|
|
71
|
+
Config.get_int("database.port") # 转成 int,失败返回默认值
|
|
72
|
+
Config.get_bool("debug") # 识别 true/1/yes/on
|
|
73
|
+
Config.get_required("database.host") # 必须存在,否则抛出 ValueError
|
|
74
|
+
Config.get_config() # 整个配置字典的副本
|
|
75
|
+
Config.clear_cache() # 清除取值缓存
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`Config.get` 的取值顺序:
|
|
79
|
+
|
|
80
|
+
1. 环境变量:以参数路径本身作为环境变量名,例如 `Config.get("database.port")` 优先读取环境变量 `database.port`。环境变量的值始终是字符串,需要数字或布尔值时请使用 `get_int` / `get_bool`。
|
|
81
|
+
2. YAML 配置:按 `a.b.c` 或 `a[0].b` 形式的路径逐级查找。
|
|
82
|
+
3. 都不存在时返回 `default`(默认为 `None`)。
|
|
83
|
+
|
|
84
|
+
注意:
|
|
85
|
+
|
|
86
|
+
- `load_config` 只在第一次调用时真正读取文件,之后再调用会直接返回已加载的配置,传入新的路径也不会重新加载。
|
|
87
|
+
- 未调用 `load_config` 就调用 `get`,会抛出 `TypeError`。
|
|
88
|
+
- `use_cache=True` 时,`get` 的结果会按路径缓存(最多 512 项);配置变化后需要调用 `clear_cache()`。
|
|
89
|
+
|
|
90
|
+
### 3. 从字符串或流中加载
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from cfgload import YamlStreamLoader
|
|
94
|
+
|
|
95
|
+
config = YamlStreamLoader(stream="host: ${DB_HOST:-localhost}\n").load()
|
|
96
|
+
print(config["host"])
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### 4. Schema 校验
|
|
100
|
+
|
|
101
|
+
传入校验器和 schema 后,`load()` 返回校验后的数据,校验失败时抛出 `cfgload.errors.ValidationError`。
|
|
102
|
+
|
|
103
|
+
以 pydantic v2 为例:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from pydantic import BaseModel
|
|
107
|
+
from cfgload import YamlLoader, PydanticV2Validator
|
|
108
|
+
|
|
109
|
+
class Database(BaseModel):
|
|
110
|
+
host: str
|
|
111
|
+
port: int
|
|
112
|
+
|
|
113
|
+
class Settings(BaseModel):
|
|
114
|
+
database: Database
|
|
115
|
+
|
|
116
|
+
config = YamlLoader(
|
|
117
|
+
path="config.yaml",
|
|
118
|
+
validator=PydanticV2Validator,
|
|
119
|
+
schema=Settings,
|
|
120
|
+
).load()
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
可用的校验器:
|
|
124
|
+
|
|
125
|
+
| 校验器 | 扩展依赖 | 说明 |
|
|
126
|
+
| --- | --- | --- |
|
|
127
|
+
| `PydanticV2Validator` | `cfgload[pydantic]` | pydantic 2.x,返回 `model_dump()` 的结果 |
|
|
128
|
+
| `PydanticValidator` | `cfgload[pydantic]` | pydantic 1.x,返回 `dict()` 的结果 |
|
|
129
|
+
| `MarshmallowValidator` | `cfgload[marshmallow]` | marshmallow 3.x |
|
|
130
|
+
| `TrafaretValidator` | `cfgload[trafaret]` | trafaret |
|
|
131
|
+
|
|
132
|
+
也可以继承 `cfgload.validators.Validator` 实现自己的校验器,只需实现 `load(data, **params)` 方法。
|
|
133
|
+
|
|
134
|
+
## 环境变量插值规则
|
|
135
|
+
|
|
136
|
+
| 写法 | 含义 |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| `${VAR}` | 替换为环境变量 `VAR` 的值;未设置时为 `None` |
|
|
139
|
+
| `${VAR:-default}` | 未设置时使用 `default` |
|
|
140
|
+
|
|
141
|
+
- 只支持整个值被替换,即 `${...}` 必须位于值的开头。`prefix-${VAR}` 不会被替换,会原样保留。
|
|
142
|
+
- 环境变量名只允许字母、数字、下划线和 `$`。
|
|
143
|
+
- 变量未设置且没有默认值时得到 `None`,不是空字符串,也不报错。
|
|
144
|
+
|
|
145
|
+
## 异常
|
|
146
|
+
|
|
147
|
+
所有异常都定义在 `cfgload.errors` 中,基类为 `ConfigError`:
|
|
148
|
+
|
|
149
|
+
| 异常 | 触发场景 |
|
|
150
|
+
| --- | --- |
|
|
151
|
+
| `LoadingError` | 文件不存在或 YAML 解析失败 |
|
|
152
|
+
| `ValidationError` | schema 校验失败 |
|
|
153
|
+
|
|
154
|
+
原始异常保存在异常对象的 `origin` 属性中。
|
|
155
|
+
|
|
156
|
+
## 开发与发布
|
|
157
|
+
|
|
158
|
+
版本号由 git 标签生成(setuptools_scm),发布前先打标签,并保持工作区干净:
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
pip install --upgrade build twine
|
|
162
|
+
|
|
163
|
+
git tag v0.1.0
|
|
164
|
+
python -m build
|
|
165
|
+
|
|
166
|
+
twine check dist/*
|
|
167
|
+
twine upload dist/*
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
未打标签时构建出的版本号形如 `0.1.dev1`,PyPI 不接受这样的版本,无法上传。
|
|
171
|
+
|
|
172
|
+
## 许可证
|
|
173
|
+
|
|
174
|
+
MIT,见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# https://packaging.python.org/en/latest/tutorials/packaging-projects/
|
|
2
|
+
# https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html
|
|
3
|
+
|
|
4
|
+
[build-system]
|
|
5
|
+
requires = ["setuptools>=77", "setuptools_scm[toml]>=6.3.1"]
|
|
6
|
+
build-backend = "setuptools.build_meta"
|
|
7
|
+
|
|
8
|
+
[project]
|
|
9
|
+
name = "yamlcfgload"
|
|
10
|
+
description = "Load YAML configs with environment variables interpolation"
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "wangxl8", email = "71364605@qq.com"},
|
|
14
|
+
]
|
|
15
|
+
dynamic = ["version"]
|
|
16
|
+
license = "MIT"
|
|
17
|
+
license-files = ["LICENSE"]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Intended Audience :: Information Technology",
|
|
22
|
+
"Intended Audience :: System Administrators",
|
|
23
|
+
"Operating System :: Unix",
|
|
24
|
+
"Operating System :: POSIX :: Linux",
|
|
25
|
+
"Environment :: Console",
|
|
26
|
+
"Environment :: MacOS X",
|
|
27
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
28
|
+
"Topic :: Internet",
|
|
29
|
+
]
|
|
30
|
+
keywords = ["yaml", "config", "configuration", "environment-variables", "interpolation"]
|
|
31
|
+
requires-python = ">=3.7"
|
|
32
|
+
dependencies = [
|
|
33
|
+
"PyYAML>=6,<7",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.optional-dependencies]
|
|
37
|
+
pydantic = ["pydantic>=0.28"]
|
|
38
|
+
marshmallow = ["marshmallow>=3"]
|
|
39
|
+
trafaret = ["trafaret>=1.2.0"]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://gitee.com/wangxinglong520/cfgload"
|
|
43
|
+
"Source code" = "https://gitee.com/wangxinglong520/cfgload"
|
|
44
|
+
"Issue tracker" = "https://gitee.com/wangxinglong520/cfgload/issues"
|
|
45
|
+
|
|
46
|
+
[tool.setuptools_scm]
|
|
47
|
+
write_to = "_version.py"
|
|
48
|
+
|
|
49
|
+
[tool.isort]
|
|
50
|
+
atomic = true
|
|
51
|
+
line_length = 88
|
|
52
|
+
skip_gitignore = true
|
|
53
|
+
known_first_party = ["cfgload"]
|
|
54
|
+
multi_line_output = 3
|
|
55
|
+
include_trailing_comma = true
|
|
56
|
+
force_grid_wrap = 0
|
|
57
|
+
|
|
58
|
+
[tool.mypy]
|
|
59
|
+
ignore_missing_imports = true
|
|
60
|
+
follow_imports = "silent"
|
|
61
|
+
strict_optional = true
|
|
62
|
+
warn_redundant_casts = true
|
|
63
|
+
warn_unused_ignores = true
|
|
64
|
+
disallow_any_generics = true
|
|
65
|
+
check_untyped_defs = true
|
|
66
|
+
|
|
67
|
+
[tool.black]
|
|
68
|
+
target-version = ["py37", "py38", "py39", "py310", "py311"]
|
|
69
|
+
line-length = 88
|
|
70
|
+
|
|
71
|
+
[tool.coverage.report]
|
|
72
|
+
fail_under = 95
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .errors import ConfigError, LoadingError, ValidationError
|
|
2
|
+
from .loaders import YamlLoader, YamlStreamLoader
|
|
3
|
+
from .matchers import Matcher, MatcherWithDefaults
|
|
4
|
+
from .validators import (
|
|
5
|
+
MarshmallowValidator,
|
|
6
|
+
PydanticV2Validator,
|
|
7
|
+
PydanticValidator,
|
|
8
|
+
TrafaretValidator,
|
|
9
|
+
)
|
|
10
|
+
from .config import Config
|
|
11
|
+
|
|
12
|
+
__all__ = ['YamlLoader', 'YamlStreamLoader', 'Config']
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
from .loaders import YamlLoader
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
path_pattern = r'(\w+)(?:\[(\d+)]?)'
|
|
8
|
+
PATH_PATTERN = re.compile(path_pattern)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Config:
|
|
12
|
+
"""配置管理类 - 支持全局配置缓存和参数获取"""
|
|
13
|
+
|
|
14
|
+
# 类级别的全局配置字典
|
|
15
|
+
_global_config: Dict = {}
|
|
16
|
+
|
|
17
|
+
# 配置是否已加载的标志
|
|
18
|
+
_is_loaded: bool = False
|
|
19
|
+
|
|
20
|
+
# 读取配置的时候是否支持从缓存读取
|
|
21
|
+
_use_cache: bool = False
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def load_config(cls, config_file_path: str = None, use_cache: bool = False) -> Dict:
|
|
25
|
+
"""
|
|
26
|
+
从配置文件加载配置到全局字典
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
config_file_path: 配置文件路径,如果指定则直接加载该文件
|
|
30
|
+
use_cache: 获取参数的时候是否缓存
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
加载后的配置字典
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if cls._is_loaded:
|
|
39
|
+
return cls._global_config
|
|
40
|
+
|
|
41
|
+
# print(f'PID={os.getpid()} load_config {config_file_path}')
|
|
42
|
+
|
|
43
|
+
if not config_file_path:
|
|
44
|
+
raise ValueError('配置文件路径不能为空')
|
|
45
|
+
|
|
46
|
+
if not os.path.exists(config_file_path):
|
|
47
|
+
raise FileNotFoundError(f'文件不存在: {config_file_path}')
|
|
48
|
+
|
|
49
|
+
# 设置缓存标志
|
|
50
|
+
cls._use_cache = use_cache
|
|
51
|
+
|
|
52
|
+
# 直接加载指定的配置文件
|
|
53
|
+
cls._global_config = YamlLoader(path=config_file_path).load()
|
|
54
|
+
cls._is_loaded = True
|
|
55
|
+
|
|
56
|
+
# 如果启用缓存,清除旧的缓存
|
|
57
|
+
if use_cache:
|
|
58
|
+
cls._get_cached.cache_clear()
|
|
59
|
+
|
|
60
|
+
return cls._global_config
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def get_config(cls) -> Dict:
|
|
64
|
+
"""
|
|
65
|
+
获取全局配置字典(只读副本)
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
全局配置的副本
|
|
69
|
+
"""
|
|
70
|
+
if not cls._is_loaded:
|
|
71
|
+
return {}
|
|
72
|
+
return cls._global_config.copy()
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def _get_from_dict(param_path: str, config_dict: Dict, default: Any = None) -> Any:
|
|
76
|
+
"""
|
|
77
|
+
从指定的字典中获取参数值(不缓存)
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
param_path: 参数路径
|
|
81
|
+
config_dict: 配置字典
|
|
82
|
+
default: 默认值
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
参数值
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def reg(string):
|
|
89
|
+
match = PATH_PATTERN.match(string)
|
|
90
|
+
if match:
|
|
91
|
+
return match.group(1), match.group(2)
|
|
92
|
+
return string, None
|
|
93
|
+
|
|
94
|
+
if not param_path:
|
|
95
|
+
return default
|
|
96
|
+
|
|
97
|
+
paths = param_path.split('.')
|
|
98
|
+
config = config_dict
|
|
99
|
+
|
|
100
|
+
for path in paths:
|
|
101
|
+
if not config or not isinstance(config, dict):
|
|
102
|
+
return default
|
|
103
|
+
key, index = reg(path)
|
|
104
|
+
config = config.get(key)
|
|
105
|
+
if config and index is not None:
|
|
106
|
+
try:
|
|
107
|
+
config = config[int(index)]
|
|
108
|
+
except (IndexError, TypeError, ValueError):
|
|
109
|
+
return default
|
|
110
|
+
|
|
111
|
+
return config if config is not None else default
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
@lru_cache(maxsize=512)
|
|
115
|
+
def _get_cached(cls, param_path: str) -> Optional[Any]:
|
|
116
|
+
"""
|
|
117
|
+
从全局配置中获取参数值(带缓存)
|
|
118
|
+
|
|
119
|
+
注意:此方法假设全局配置已经加载
|
|
120
|
+
注意:当配置重载时,需要调用 cache_clear()
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
param_path: 参数路径,如 'db.host' 或 'cache.ttl'
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
参数值,如果不存在则返回 None
|
|
127
|
+
"""
|
|
128
|
+
return cls._get_from_dict(param_path, cls._global_config)
|
|
129
|
+
|
|
130
|
+
@classmethod
|
|
131
|
+
def get(cls, param_path: str, default: Any = None) -> Any:
|
|
132
|
+
"""
|
|
133
|
+
获取配置参数
|
|
134
|
+
|
|
135
|
+
优先从环境变量获取,然后从全局配置中获取
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
param_path: 参数路径,如 'db.host' 或 'cache.ttl'
|
|
139
|
+
default: 默认值,当参数不存在时返回
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
参数值,如果不存在则返回 default
|
|
143
|
+
|
|
144
|
+
Examples:
|
|
145
|
+
>>> Config.load_config('dev')
|
|
146
|
+
>>> Config.get('database.host')
|
|
147
|
+
'localhost'
|
|
148
|
+
>>> Config.get('database.port', 3306)
|
|
149
|
+
3306
|
|
150
|
+
>>> Config.get('cache.redis[0].host')
|
|
151
|
+
'127.0.0.1'
|
|
152
|
+
"""
|
|
153
|
+
# 1. 优先从环境变量获取
|
|
154
|
+
env_value = os.getenv(param_path)
|
|
155
|
+
if env_value is not None:
|
|
156
|
+
return env_value
|
|
157
|
+
|
|
158
|
+
# 2. 确保全局配置已加载
|
|
159
|
+
if not cls._is_loaded:
|
|
160
|
+
raise TypeError(f'配置文件未加载')
|
|
161
|
+
|
|
162
|
+
# 3. 从全局配置获取
|
|
163
|
+
if cls._use_cache:
|
|
164
|
+
# 使用缓存版本
|
|
165
|
+
value = cls._get_cached(param_path)
|
|
166
|
+
else:
|
|
167
|
+
# 不使用缓存,直接获取
|
|
168
|
+
value = cls._get_from_dict(param_path, cls._global_config)
|
|
169
|
+
|
|
170
|
+
# 4. 返回结果
|
|
171
|
+
return value if value is not None else default
|
|
172
|
+
|
|
173
|
+
@classmethod
|
|
174
|
+
def clear_cache(cls):
|
|
175
|
+
"""仅清除缓存,不重新加载配置"""
|
|
176
|
+
cls._get_cached.cache_clear()
|
|
177
|
+
|
|
178
|
+
@classmethod
|
|
179
|
+
def get_int(cls, param_path: str, default: int = None) -> Optional[int]:
|
|
180
|
+
"""获取整数类型的配置参数"""
|
|
181
|
+
value = cls.get(param_path)
|
|
182
|
+
if value is None:
|
|
183
|
+
return default
|
|
184
|
+
try:
|
|
185
|
+
return int(value)
|
|
186
|
+
except (ValueError, TypeError):
|
|
187
|
+
return default
|
|
188
|
+
|
|
189
|
+
@classmethod
|
|
190
|
+
def get_bool(cls, param_path: str, default: bool = None) -> Optional[bool]:
|
|
191
|
+
"""获取布尔类型的配置参数"""
|
|
192
|
+
value = cls.get(param_path)
|
|
193
|
+
if value is None:
|
|
194
|
+
return default
|
|
195
|
+
if isinstance(value, bool):
|
|
196
|
+
return value
|
|
197
|
+
if isinstance(value, str):
|
|
198
|
+
return value.lower() in ('true', '1', 'yes', 'on')
|
|
199
|
+
return bool(value)
|
|
200
|
+
|
|
201
|
+
@classmethod
|
|
202
|
+
def get_required(cls, param_path: str) -> Any:
|
|
203
|
+
"""获取必需的配置参数(必须存在)"""
|
|
204
|
+
value = cls.get(param_path)
|
|
205
|
+
if value is None:
|
|
206
|
+
raise ValueError(f"必需的配置参数 '{param_path}' 未设置")
|
|
207
|
+
return value
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from typing import Any, Optional
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ConfigErrorMixin:
|
|
5
|
+
"""
|
|
6
|
+
Mixin class to wrap and format original exception
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
msg_template: str
|
|
10
|
+
|
|
11
|
+
def __init__(self, origin: Optional[Exception] = None, **context: Any) -> None:
|
|
12
|
+
"""
|
|
13
|
+
Mixing for wrapping original exception
|
|
14
|
+
|
|
15
|
+
:param origin: original exception,
|
|
16
|
+
may be helpful when special method invocation needed
|
|
17
|
+
:param context: mapping used for exception message formatting
|
|
18
|
+
"""
|
|
19
|
+
self.origin = origin
|
|
20
|
+
self.context = context or None
|
|
21
|
+
super().__init__()
|
|
22
|
+
|
|
23
|
+
def __str__(self) -> str:
|
|
24
|
+
return self.msg_template.format(**self.context or {})
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ConfigError(ConfigErrorMixin, Exception):
|
|
28
|
+
"""
|
|
29
|
+
Base class for Piny exceptions
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class LoadingError(ConfigError):
|
|
36
|
+
"""
|
|
37
|
+
Exception for reading or parsing configuration file errors
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
msg_template = "Loading YAML file failed: {reason}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ValidationError(ConfigError):
|
|
44
|
+
"""
|
|
45
|
+
Exception for data validation errors
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
msg_template = "Validation failed: {reason}"
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import yaml
|
|
2
|
+
from typing import IO, Any, Type, Union
|
|
3
|
+
from .errors import LoadingError
|
|
4
|
+
from .matchers import Matcher, MatcherWithDefaults
|
|
5
|
+
from .validators import Validator
|
|
6
|
+
|
|
7
|
+
#
|
|
8
|
+
# Loader
|
|
9
|
+
#
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class YamlLoader:
|
|
13
|
+
"""
|
|
14
|
+
YAML configuration file loader
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
path: str = "",
|
|
20
|
+
*,
|
|
21
|
+
matcher: Type[Matcher] = MatcherWithDefaults,
|
|
22
|
+
validator: Union[Type[Validator], None] = None,
|
|
23
|
+
schema: Any = None,
|
|
24
|
+
**schema_params,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Initialize YAML loader
|
|
28
|
+
|
|
29
|
+
:param path: string with path to YAML-file
|
|
30
|
+
:param matcher: matcher class
|
|
31
|
+
:param validator: validator class for one of the supported validation libraries
|
|
32
|
+
:param schema: validation schema for the validator of choice
|
|
33
|
+
:param schema_params: named arguments used as optional validation schema params
|
|
34
|
+
"""
|
|
35
|
+
self.path = path
|
|
36
|
+
self.matcher = matcher
|
|
37
|
+
self.validator = validator
|
|
38
|
+
self.schema = schema
|
|
39
|
+
self.schema_params = schema_params
|
|
40
|
+
|
|
41
|
+
def _init_resolvers(self):
|
|
42
|
+
self.matcher.add_implicit_resolver("!env", self.matcher.matcher, None)
|
|
43
|
+
self.matcher.add_constructor("!env", self.matcher.constructor)
|
|
44
|
+
|
|
45
|
+
def load(self, **params) -> Any:
|
|
46
|
+
"""
|
|
47
|
+
Return Python object loaded (optionally validated) from the YAML-file
|
|
48
|
+
|
|
49
|
+
:param params: named arguments used as optional loading params in validation
|
|
50
|
+
"""
|
|
51
|
+
self._init_resolvers()
|
|
52
|
+
try:
|
|
53
|
+
with open(self.path, 'r', encoding='utf-8') as fh:
|
|
54
|
+
load = yaml.load(fh, Loader=self.matcher)
|
|
55
|
+
except (yaml.YAMLError, FileNotFoundError) as e:
|
|
56
|
+
raise LoadingError(origin=e, reason=str(e))
|
|
57
|
+
|
|
58
|
+
if (self.validator is not None) and (self.schema is not None):
|
|
59
|
+
return self.validator(self.schema, **self.schema_params).load(
|
|
60
|
+
data=load, **params
|
|
61
|
+
)
|
|
62
|
+
return load
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class YamlStreamLoader(YamlLoader):
|
|
66
|
+
"""
|
|
67
|
+
YAML configuration loader for IO streams, e.g. file objects or stdin
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
stream: Union[str, IO[str]],
|
|
73
|
+
*,
|
|
74
|
+
matcher: Type[Matcher] = MatcherWithDefaults,
|
|
75
|
+
validator: Union[Type[Validator], None] = None,
|
|
76
|
+
schema: Any = None,
|
|
77
|
+
**schema_params,
|
|
78
|
+
) -> None:
|
|
79
|
+
super().__init__()
|
|
80
|
+
self.stream = stream
|
|
81
|
+
self.matcher = matcher
|
|
82
|
+
self.validator = validator
|
|
83
|
+
self.schema = schema
|
|
84
|
+
self.schema_params = schema_params
|
|
85
|
+
|
|
86
|
+
def load(self, **params) -> Any:
|
|
87
|
+
self._init_resolvers()
|
|
88
|
+
try:
|
|
89
|
+
load = yaml.load(self.stream, Loader=self.matcher)
|
|
90
|
+
except yaml.YAMLError as e:
|
|
91
|
+
raise LoadingError(origin=e, reason=str(e))
|
|
92
|
+
|
|
93
|
+
if (self.validator is not None) and (self.schema is not None):
|
|
94
|
+
return self.validator(self.schema, **self.schema_params).load(
|
|
95
|
+
data=load, **params
|
|
96
|
+
)
|
|
97
|
+
return load
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
import yaml
|
|
4
|
+
from typing import Pattern
|
|
5
|
+
|
|
6
|
+
class Matcher(yaml.SafeLoader):
|
|
7
|
+
"""
|
|
8
|
+
Base class for matchers
|
|
9
|
+
|
|
10
|
+
Use this class only to derive new child classes
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
matcher: Pattern[str] = re.compile("")
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
def constructor(loader, node):
|
|
17
|
+
raise NotImplementedError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MatcherWithDefaults(Matcher):
|
|
21
|
+
"""
|
|
22
|
+
Expand an environment variable with its value
|
|
23
|
+
|
|
24
|
+
Forms supported: ${VAR}, ${VAR:-default}
|
|
25
|
+
If value is not set and no default value given return None.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
matcher = re.compile(r"\$\{([a-zA-Z_$0-9]+)(:-.*)?\}")
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def constructor(loader, node):
|
|
32
|
+
match = MatcherWithDefaults.matcher.match(node.value)
|
|
33
|
+
variable, default = match.groups() # type: ignore
|
|
34
|
+
|
|
35
|
+
if default:
|
|
36
|
+
# lstrip() is dangerous!
|
|
37
|
+
# It can remove legitimate first two letters in a value starting with `:-`
|
|
38
|
+
default = default[2:]
|
|
39
|
+
|
|
40
|
+
return os.environ.get(variable, default)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any, Dict, List, Union
|
|
3
|
+
|
|
4
|
+
from .errors import ValidationError
|
|
5
|
+
|
|
6
|
+
LoadedData = Union[Dict[str, Any], List[Any]]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Validator(ABC):
|
|
10
|
+
"""
|
|
11
|
+
Abstract base class for optional validator classes
|
|
12
|
+
|
|
13
|
+
Use only to derive new child classes, implement all abstract methods
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, schema: Any, **params):
|
|
17
|
+
self.schema = schema
|
|
18
|
+
self.schema_params = params
|
|
19
|
+
|
|
20
|
+
@abstractmethod
|
|
21
|
+
def load(self, data: LoadedData, **params):
|
|
22
|
+
"""
|
|
23
|
+
Load data, return validated data or raise en error
|
|
24
|
+
"""
|
|
25
|
+
pass # pragma: no cover
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PydanticValidator(Validator): # pragma: no cover
|
|
29
|
+
"""
|
|
30
|
+
Validator class for Pydantic Version 1
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def load(self, data: LoadedData, **params):
|
|
34
|
+
try:
|
|
35
|
+
return self.schema(**data).dict()
|
|
36
|
+
except Exception as e:
|
|
37
|
+
raise ValidationError(origin=e, reason=str(e))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PydanticV2Validator(Validator):
|
|
41
|
+
"""
|
|
42
|
+
Validator class for Pydantic Version 2
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def load(self, data: LoadedData, **params):
|
|
46
|
+
try:
|
|
47
|
+
return self.schema(**data).model_dump()
|
|
48
|
+
except Exception as e:
|
|
49
|
+
raise ValidationError(origin=e, reason=str(e))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class MarshmallowValidator(Validator):
|
|
53
|
+
"""
|
|
54
|
+
Validator class for Marshmallow library
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def load(self, data: LoadedData, **params):
|
|
58
|
+
try:
|
|
59
|
+
return self.schema(**self.schema_params).load(data, **params)
|
|
60
|
+
except Exception as e:
|
|
61
|
+
raise ValidationError(origin=e, reason=str(e))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TrafaretValidator(Validator):
|
|
65
|
+
"""
|
|
66
|
+
Validator class for Trafaret library
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def load(self, data: LoadedData, **params):
|
|
70
|
+
try:
|
|
71
|
+
return self.schema.check(data)
|
|
72
|
+
except Exception as e:
|
|
73
|
+
raise ValidationError(origin=e, reason=str(e))
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: yamlcfgload
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Load YAML configs with environment variables interpolation
|
|
5
|
+
Author-email: wangxl8 <71364605@qq.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gitee.com/wangxinglong520/cfgload
|
|
8
|
+
Project-URL: Source code, https://gitee.com/wangxinglong520/cfgload
|
|
9
|
+
Project-URL: Issue tracker, https://gitee.com/wangxinglong520/cfgload/issues
|
|
10
|
+
Keywords: yaml,config,configuration,environment-variables,interpolation
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Information Technology
|
|
14
|
+
Classifier: Intended Audience :: System Administrators
|
|
15
|
+
Classifier: Operating System :: Unix
|
|
16
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
17
|
+
Classifier: Environment :: Console
|
|
18
|
+
Classifier: Environment :: MacOS X
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: Internet
|
|
21
|
+
Requires-Python: >=3.7
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: PyYAML<7,>=6
|
|
25
|
+
Provides-Extra: pydantic
|
|
26
|
+
Requires-Dist: pydantic>=0.28; extra == "pydantic"
|
|
27
|
+
Provides-Extra: marshmallow
|
|
28
|
+
Requires-Dist: marshmallow>=3; extra == "marshmallow"
|
|
29
|
+
Provides-Extra: trafaret
|
|
30
|
+
Requires-Dist: trafaret>=1.2.0; extra == "trafaret"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# yamlcfgload
|
|
34
|
+
|
|
35
|
+
从 YAML 文件加载配置,支持环境变量插值和可选的 schema 校验。
|
|
36
|
+
|
|
37
|
+
包名为 `yamlcfgload`,导入名为 `cfgload`。
|
|
38
|
+
|
|
39
|
+
## 特性
|
|
40
|
+
|
|
41
|
+
- 在 YAML 中用 `${VAR}` 引用环境变量,用 `${VAR:-default}` 指定默认值
|
|
42
|
+
- 基于 `yaml.SafeLoader`,不执行任意 Python 对象
|
|
43
|
+
- 可选的 schema 校验,支持 pydantic、marshmallow、trafaret
|
|
44
|
+
- `Config` 类:一次加载、全局访问,支持点号路径、列表下标、环境变量覆盖和取值缓存
|
|
45
|
+
|
|
46
|
+
## 安装
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install yamlcfgload
|
|
50
|
+
# 可选的校验器扩展
|
|
51
|
+
pip install "yamlcfgload[pydantic]"
|
|
52
|
+
pip install "yamlcfgload[marshmallow]"
|
|
53
|
+
pip install "yamlcfgload[trafaret]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
要求 Python 3.7+,核心依赖只有 PyYAML。
|
|
57
|
+
|
|
58
|
+
## 快速开始
|
|
59
|
+
|
|
60
|
+
### 1. 加载 YAML 并插值环境变量
|
|
61
|
+
|
|
62
|
+
`config.yaml`:
|
|
63
|
+
|
|
64
|
+
```yaml
|
|
65
|
+
database:
|
|
66
|
+
host: ${DB_HOST:-localhost}
|
|
67
|
+
port: 5432
|
|
68
|
+
user: ${DB_USER}
|
|
69
|
+
cache:
|
|
70
|
+
- host: 127.0.0.1
|
|
71
|
+
ttl: 60
|
|
72
|
+
debug: true
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from cfgload import YamlLoader
|
|
77
|
+
|
|
78
|
+
config = YamlLoader(path="config.yaml").load()
|
|
79
|
+
|
|
80
|
+
print(config["database"]["host"]) # 环境变量 DB_HOST 的值;未设置时为 localhost
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
环境变量未设置且没有默认值时,该项为 `None`:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
import os
|
|
87
|
+
from cfgload import YamlLoader
|
|
88
|
+
|
|
89
|
+
os.environ.pop("DB_USER", None)
|
|
90
|
+
print(YamlLoader(path="config.yaml").load()["database"]["user"]) # None
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### 2. 使用 Config 管理全局配置
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from cfgload import Config
|
|
97
|
+
|
|
98
|
+
Config.load_config("config.yaml", use_cache=True)
|
|
99
|
+
|
|
100
|
+
Config.get("database.host") # 点号路径取值
|
|
101
|
+
Config.get("database.port", 3306) # 不存在时返回默认值
|
|
102
|
+
Config.get("cache[0].ttl") # 列表下标
|
|
103
|
+
Config.get_int("database.port") # 转成 int,失败返回默认值
|
|
104
|
+
Config.get_bool("debug") # 识别 true/1/yes/on
|
|
105
|
+
Config.get_required("database.host") # 必须存在,否则抛出 ValueError
|
|
106
|
+
Config.get_config() # 整个配置字典的副本
|
|
107
|
+
Config.clear_cache() # 清除取值缓存
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`Config.get` 的取值顺序:
|
|
111
|
+
|
|
112
|
+
1. 环境变量:以参数路径本身作为环境变量名,例如 `Config.get("database.port")` 优先读取环境变量 `database.port`。环境变量的值始终是字符串,需要数字或布尔值时请使用 `get_int` / `get_bool`。
|
|
113
|
+
2. YAML 配置:按 `a.b.c` 或 `a[0].b` 形式的路径逐级查找。
|
|
114
|
+
3. 都不存在时返回 `default`(默认为 `None`)。
|
|
115
|
+
|
|
116
|
+
注意:
|
|
117
|
+
|
|
118
|
+
- `load_config` 只在第一次调用时真正读取文件,之后再调用会直接返回已加载的配置,传入新的路径也不会重新加载。
|
|
119
|
+
- 未调用 `load_config` 就调用 `get`,会抛出 `TypeError`。
|
|
120
|
+
- `use_cache=True` 时,`get` 的结果会按路径缓存(最多 512 项);配置变化后需要调用 `clear_cache()`。
|
|
121
|
+
|
|
122
|
+
### 3. 从字符串或流中加载
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from cfgload import YamlStreamLoader
|
|
126
|
+
|
|
127
|
+
config = YamlStreamLoader(stream="host: ${DB_HOST:-localhost}\n").load()
|
|
128
|
+
print(config["host"])
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### 4. Schema 校验
|
|
132
|
+
|
|
133
|
+
传入校验器和 schema 后,`load()` 返回校验后的数据,校验失败时抛出 `cfgload.errors.ValidationError`。
|
|
134
|
+
|
|
135
|
+
以 pydantic v2 为例:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from pydantic import BaseModel
|
|
139
|
+
from cfgload import YamlLoader, PydanticV2Validator
|
|
140
|
+
|
|
141
|
+
class Database(BaseModel):
|
|
142
|
+
host: str
|
|
143
|
+
port: int
|
|
144
|
+
|
|
145
|
+
class Settings(BaseModel):
|
|
146
|
+
database: Database
|
|
147
|
+
|
|
148
|
+
config = YamlLoader(
|
|
149
|
+
path="config.yaml",
|
|
150
|
+
validator=PydanticV2Validator,
|
|
151
|
+
schema=Settings,
|
|
152
|
+
).load()
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
可用的校验器:
|
|
156
|
+
|
|
157
|
+
| 校验器 | 扩展依赖 | 说明 |
|
|
158
|
+
| --- | --- | --- |
|
|
159
|
+
| `PydanticV2Validator` | `cfgload[pydantic]` | pydantic 2.x,返回 `model_dump()` 的结果 |
|
|
160
|
+
| `PydanticValidator` | `cfgload[pydantic]` | pydantic 1.x,返回 `dict()` 的结果 |
|
|
161
|
+
| `MarshmallowValidator` | `cfgload[marshmallow]` | marshmallow 3.x |
|
|
162
|
+
| `TrafaretValidator` | `cfgload[trafaret]` | trafaret |
|
|
163
|
+
|
|
164
|
+
也可以继承 `cfgload.validators.Validator` 实现自己的校验器,只需实现 `load(data, **params)` 方法。
|
|
165
|
+
|
|
166
|
+
## 环境变量插值规则
|
|
167
|
+
|
|
168
|
+
| 写法 | 含义 |
|
|
169
|
+
| --- | --- |
|
|
170
|
+
| `${VAR}` | 替换为环境变量 `VAR` 的值;未设置时为 `None` |
|
|
171
|
+
| `${VAR:-default}` | 未设置时使用 `default` |
|
|
172
|
+
|
|
173
|
+
- 只支持整个值被替换,即 `${...}` 必须位于值的开头。`prefix-${VAR}` 不会被替换,会原样保留。
|
|
174
|
+
- 环境变量名只允许字母、数字、下划线和 `$`。
|
|
175
|
+
- 变量未设置且没有默认值时得到 `None`,不是空字符串,也不报错。
|
|
176
|
+
|
|
177
|
+
## 异常
|
|
178
|
+
|
|
179
|
+
所有异常都定义在 `cfgload.errors` 中,基类为 `ConfigError`:
|
|
180
|
+
|
|
181
|
+
| 异常 | 触发场景 |
|
|
182
|
+
| --- | --- |
|
|
183
|
+
| `LoadingError` | 文件不存在或 YAML 解析失败 |
|
|
184
|
+
| `ValidationError` | schema 校验失败 |
|
|
185
|
+
|
|
186
|
+
原始异常保存在异常对象的 `origin` 属性中。
|
|
187
|
+
|
|
188
|
+
## 开发与发布
|
|
189
|
+
|
|
190
|
+
版本号由 git 标签生成(setuptools_scm),发布前先打标签,并保持工作区干净:
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
pip install --upgrade build twine
|
|
194
|
+
|
|
195
|
+
git tag v0.1.0
|
|
196
|
+
python -m build
|
|
197
|
+
|
|
198
|
+
twine check dist/*
|
|
199
|
+
twine upload dist/*
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
未打标签时构建出的版本号形如 `0.1.dev1`,PyPI 不接受这样的版本,无法上传。
|
|
203
|
+
|
|
204
|
+
## 许可证
|
|
205
|
+
|
|
206
|
+
MIT,见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
.gitignore
|
|
2
|
+
LICENSE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/cfgload/__init__.py
|
|
6
|
+
src/cfgload/config.py
|
|
7
|
+
src/cfgload/errors.py
|
|
8
|
+
src/cfgload/loaders.py
|
|
9
|
+
src/cfgload/matchers.py
|
|
10
|
+
src/cfgload/validators.py
|
|
11
|
+
src/yamlcfgload.egg-info/PKG-INFO
|
|
12
|
+
src/yamlcfgload.egg-info/SOURCES.txt
|
|
13
|
+
src/yamlcfgload.egg-info/dependency_links.txt
|
|
14
|
+
src/yamlcfgload.egg-info/requires.txt
|
|
15
|
+
src/yamlcfgload.egg-info/scm_file_list.json
|
|
16
|
+
src/yamlcfgload.egg-info/scm_version.json
|
|
17
|
+
src/yamlcfgload.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"files": [
|
|
3
|
+
".gitignore",
|
|
4
|
+
"LICENSE",
|
|
5
|
+
"README.md",
|
|
6
|
+
"pyproject.toml",
|
|
7
|
+
"src\\cfgload\\__init__.py",
|
|
8
|
+
"src\\cfgload\\config.py",
|
|
9
|
+
"src\\cfgload\\errors.py",
|
|
10
|
+
"src\\cfgload\\loaders.py",
|
|
11
|
+
"src\\cfgload\\matchers.py",
|
|
12
|
+
"src\\cfgload\\validators.py"
|
|
13
|
+
]
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cfgload
|