confull 0.0.1__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.
- confull-0.0.1/LICENSE +201 -0
- confull-0.0.1/PKG-INFO +187 -0
- confull-0.0.1/README.md +164 -0
- confull-0.0.1/confull/__init__.py +4 -0
- confull-0.0.1/confull/config.py +619 -0
- confull-0.0.1/pyproject.toml +19 -0
confull-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
confull-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: confull
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: 一个简单的配置管理工具(A simple dictionary configuration management tool),dict <-> config file [json, toml, yaml, ini, xml]
|
|
5
|
+
Author: zisul
|
|
6
|
+
Author-email: zisull@qq.com
|
|
7
|
+
Requires-Python: >=3.6,<4.0
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Dist: configparser (>=7.1.0,<8.0.0)
|
|
18
|
+
Requires-Dist: orjson (>=3.10.11,<4.0.0)
|
|
19
|
+
Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
|
|
20
|
+
Requires-Dist: toml (>=0.10.2,<0.11.0)
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# confull 多格式配置管理器说明文档
|
|
24
|
+
|
|
25
|
+
[Zh](https://github.com/zisull/confull/blob/main/README.md) / [En](https://github.com/zisull/confull/blob/main/doc/README-en.md)
|
|
26
|
+
|
|
27
|
+
## 一、概述
|
|
28
|
+
|
|
29
|
+
```cmd
|
|
30
|
+
pip install confull
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 一、概述
|
|
34
|
+
|
|
35
|
+
本配置管理器是一个多格式的配置管理工具,支持 `dict` 与 `ini`、`xml`、`json`、`toml`、`yaml` 等格式的读写与自动保存。它提供了便捷的接口来管理配置数据,并且可以根据需要切换配置文件和格式。
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
## 二、类和方法说明
|
|
40
|
+
|
|
41
|
+
### 1. `Config` 类
|
|
42
|
+
|
|
43
|
+
该类是配置管理器的核心类,负责管理配置数据的读写、保存等操作。
|
|
44
|
+
|
|
45
|
+
#### 初始化方法 `__init__`
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
def __init__(self, data: dict = None, file: str = "config", way: str = "toml", replace: bool = False,
|
|
49
|
+
auto_save: bool = True, backup: bool = False):
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- 参数说明
|
|
53
|
+
- `data`:初始配置数据,类型为 `dict`,默认为 `None`。
|
|
54
|
+
- `file`:配置文件名(可无扩展名),默认为 `"config"`。
|
|
55
|
+
- `way`:配置文件格式,支持 `json`、`toml`、`yaml`、`ini`、`xml`,默认为 `"toml"`。
|
|
56
|
+
- `replace`:是否覆盖已有配置文件,布尔值,默认为 `False`。
|
|
57
|
+
- `auto_save`:是否自动保存,布尔值,默认为 `True`。
|
|
58
|
+
- `backup`:是否备份原配置文件,布尔值,默认为 `False`。
|
|
59
|
+
|
|
60
|
+
#### 属性
|
|
61
|
+
|
|
62
|
+
- `json`:以 json 字符串格式返回配置数据。
|
|
63
|
+
- `dict`:以 `dict` 格式返回配置数据,也可用于批量设置配置数据。
|
|
64
|
+
- `auto_save`:是否自动保存,可读写属性。
|
|
65
|
+
- `backup`:是否备份原配置文件,可读写属性。
|
|
66
|
+
- `str`:以字符串格式返回配置数据。
|
|
67
|
+
- `file_path`:配置文件路径。
|
|
68
|
+
- `file_path_abs`:配置文件绝对路径。
|
|
69
|
+
|
|
70
|
+
#### 方法
|
|
71
|
+
|
|
72
|
+
- `read(key: str, default=None)`:读取配置项,支持点号路径,如 `a.b.c`。若配置项不存在,返回默认值。
|
|
73
|
+
- `write(key: str, value, overwrite_mode: bool = False)`:写入配置项,支持点号路径。若 `overwrite_mode` 为 `True`,路径冲突时会覆盖。写入后若 `auto_save` 为 `True`,则自动保存。
|
|
74
|
+
- `del_clean()`:清空所有配置并删除配置文件。
|
|
75
|
+
- `update(data: dict)`:批量更新配置项,支持点号路径。更新后若 `auto_save` 为 `True`,则自动保存。
|
|
76
|
+
- `set_data(data: dict)`:用 `dict` 完全替换配置数据。替换后若 `auto_save` 为 `True`,则自动保存。
|
|
77
|
+
- `del_key(key: str)`:删除指定配置项,支持点号路径。删除后若 `auto_save` 为 `True`,则自动保存。
|
|
78
|
+
- `_load()`:从文件加载配置,内部方法。
|
|
79
|
+
- `load(file: str = None, way: str = None)`:切换配置文件或格式(不自动加载内容)。
|
|
80
|
+
- `mark_dirty()`:标记配置已更改。
|
|
81
|
+
- `save()`:保存配置到文件。
|
|
82
|
+
- `save_to_file(file: str = None, way: str = None)`:另存为指定文件和格式。
|
|
83
|
+
- `_ensure_file_exists()`:确保配置文件存在,内部方法。
|
|
84
|
+
- `_backup_file()`:备份原配置文件,内部方法。
|
|
85
|
+
- `_recursive_update(original, new_data)`:递归更新配置,支持点号路径,内部方法。
|
|
86
|
+
- `validate_format(_way)`:校验并返回合法格式名,静态方法。
|
|
87
|
+
- `ensure_extension(file)`:确保文件名有正确扩展名。
|
|
88
|
+
|
|
89
|
+
## 三、使用示例
|
|
90
|
+
|
|
91
|
+
### 1. 初始化配置管理器
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from confull import Config
|
|
95
|
+
|
|
96
|
+
# 使用默认参数初始化
|
|
97
|
+
config = Config()
|
|
98
|
+
|
|
99
|
+
# 使用自定义参数初始化
|
|
100
|
+
data = {'a': {'b': 'c'}}
|
|
101
|
+
config = Config(data=data, file='custom_config', way='json')
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### 2. 读取和写入配置项
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
# 写入配置项
|
|
108
|
+
config.write('a.b', 'new_value') # 也可以写为 : config.a.b = 'new_value'
|
|
109
|
+
# 读取配置项
|
|
110
|
+
value = config.read('a.b') # value = config.a.b
|
|
111
|
+
print(value) # 输出: new_value
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 3. 批量更新配置项
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
new_data = {'a': {'b': 'updated_value'}, 'd': 'e'}
|
|
118
|
+
config.update(new_data)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 4. 保存和另存配置文件
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
# 保存配置文件
|
|
125
|
+
config.save()
|
|
126
|
+
|
|
127
|
+
# 另存为指定文件和格式
|
|
128
|
+
config.save_to_file(file='backup_config', way='yaml')
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### 5. 删除配置项和清空配置
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
# 删除配置项
|
|
135
|
+
config.del_key('a.b')
|
|
136
|
+
|
|
137
|
+
# 清空配置并删除文件
|
|
138
|
+
config.del_clean()
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### 6.# 读写方法示例
|
|
142
|
+
|
|
143
|
+
```
|
|
144
|
+
# 读写方法示例
|
|
145
|
+
from confull import Config
|
|
146
|
+
|
|
147
|
+
cc = Config()
|
|
148
|
+
cc.write('学校名称', '大学')
|
|
149
|
+
cc.学校.日期 = "2021-01-01"
|
|
150
|
+
print(cc.read('学校.日期'))
|
|
151
|
+
print(cc['学校名称'])
|
|
152
|
+
print(cc.学校.日期)
|
|
153
|
+
print(cc)
|
|
154
|
+
cc.pop('学校名称')
|
|
155
|
+
print(cc)
|
|
156
|
+
cc.clear() # 字典方式清空配置data
|
|
157
|
+
print(cc)
|
|
158
|
+
cc.del_clean()
|
|
159
|
+
|
|
160
|
+
# 字典方式设置值示例
|
|
161
|
+
cc = Config()
|
|
162
|
+
cc.dict = {'地点': '北京', '图书': {'数量': 100, '价格': 10.5}, '学生': {'数量': 1000, '年龄': 20}}
|
|
163
|
+
print(cc)
|
|
164
|
+
cc.del_clean()
|
|
165
|
+
|
|
166
|
+
# 强制覆写示例
|
|
167
|
+
dic_ = {'学校': 'pass'}
|
|
168
|
+
cc = Config(data=dic_)
|
|
169
|
+
cc.write('学校.大学', '大学', overwrite_mode=True) # overwrite_mode=True 强制覆写,但会导致原路径被删除
|
|
170
|
+
print(cc)
|
|
171
|
+
cc.del_clean()
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
## 四、注意事项
|
|
177
|
+
|
|
178
|
+
- 当使用 `write`、`update`、`set_data`、`del_key` 等方法修改配置数据时,若 `auto_save` 为 `True`,会自动保存配置文件。
|
|
179
|
+
- 若配置文件格式不支持,会抛出 `ValueError` 异常。
|
|
180
|
+
- 在使用 `INIConfigHandler` 保存配置时,若数据不是嵌套字典,会将其包装在一个默认的 `'默认'` 节中。
|
|
181
|
+
|
|
182
|
+
## 尾语
|
|
183
|
+
|
|
184
|
+
作者水平有限,尽可能简化配置文件的读写流程,让使用者可以用一种更加直观、便捷的方式去操作配置信息。
|
|
185
|
+
|
|
186
|
+
2024 年 11 月 19 日 zisull@qq.com
|
|
187
|
+
|
confull-0.0.1/README.md
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# confull 多格式配置管理器说明文档
|
|
2
|
+
|
|
3
|
+
[Zh](https://github.com/zisull/confull/blob/main/README.md) / [En](https://github.com/zisull/confull/blob/main/doc/README-en.md)
|
|
4
|
+
|
|
5
|
+
## 一、概述
|
|
6
|
+
|
|
7
|
+
```cmd
|
|
8
|
+
pip install confull
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## 一、概述
|
|
12
|
+
|
|
13
|
+
本配置管理器是一个多格式的配置管理工具,支持 `dict` 与 `ini`、`xml`、`json`、`toml`、`yaml` 等格式的读写与自动保存。它提供了便捷的接口来管理配置数据,并且可以根据需要切换配置文件和格式。
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
## 二、类和方法说明
|
|
18
|
+
|
|
19
|
+
### 1. `Config` 类
|
|
20
|
+
|
|
21
|
+
该类是配置管理器的核心类,负责管理配置数据的读写、保存等操作。
|
|
22
|
+
|
|
23
|
+
#### 初始化方法 `__init__`
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
def __init__(self, data: dict = None, file: str = "config", way: str = "toml", replace: bool = False,
|
|
27
|
+
auto_save: bool = True, backup: bool = False):
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- 参数说明
|
|
31
|
+
- `data`:初始配置数据,类型为 `dict`,默认为 `None`。
|
|
32
|
+
- `file`:配置文件名(可无扩展名),默认为 `"config"`。
|
|
33
|
+
- `way`:配置文件格式,支持 `json`、`toml`、`yaml`、`ini`、`xml`,默认为 `"toml"`。
|
|
34
|
+
- `replace`:是否覆盖已有配置文件,布尔值,默认为 `False`。
|
|
35
|
+
- `auto_save`:是否自动保存,布尔值,默认为 `True`。
|
|
36
|
+
- `backup`:是否备份原配置文件,布尔值,默认为 `False`。
|
|
37
|
+
|
|
38
|
+
#### 属性
|
|
39
|
+
|
|
40
|
+
- `json`:以 json 字符串格式返回配置数据。
|
|
41
|
+
- `dict`:以 `dict` 格式返回配置数据,也可用于批量设置配置数据。
|
|
42
|
+
- `auto_save`:是否自动保存,可读写属性。
|
|
43
|
+
- `backup`:是否备份原配置文件,可读写属性。
|
|
44
|
+
- `str`:以字符串格式返回配置数据。
|
|
45
|
+
- `file_path`:配置文件路径。
|
|
46
|
+
- `file_path_abs`:配置文件绝对路径。
|
|
47
|
+
|
|
48
|
+
#### 方法
|
|
49
|
+
|
|
50
|
+
- `read(key: str, default=None)`:读取配置项,支持点号路径,如 `a.b.c`。若配置项不存在,返回默认值。
|
|
51
|
+
- `write(key: str, value, overwrite_mode: bool = False)`:写入配置项,支持点号路径。若 `overwrite_mode` 为 `True`,路径冲突时会覆盖。写入后若 `auto_save` 为 `True`,则自动保存。
|
|
52
|
+
- `del_clean()`:清空所有配置并删除配置文件。
|
|
53
|
+
- `update(data: dict)`:批量更新配置项,支持点号路径。更新后若 `auto_save` 为 `True`,则自动保存。
|
|
54
|
+
- `set_data(data: dict)`:用 `dict` 完全替换配置数据。替换后若 `auto_save` 为 `True`,则自动保存。
|
|
55
|
+
- `del_key(key: str)`:删除指定配置项,支持点号路径。删除后若 `auto_save` 为 `True`,则自动保存。
|
|
56
|
+
- `_load()`:从文件加载配置,内部方法。
|
|
57
|
+
- `load(file: str = None, way: str = None)`:切换配置文件或格式(不自动加载内容)。
|
|
58
|
+
- `mark_dirty()`:标记配置已更改。
|
|
59
|
+
- `save()`:保存配置到文件。
|
|
60
|
+
- `save_to_file(file: str = None, way: str = None)`:另存为指定文件和格式。
|
|
61
|
+
- `_ensure_file_exists()`:确保配置文件存在,内部方法。
|
|
62
|
+
- `_backup_file()`:备份原配置文件,内部方法。
|
|
63
|
+
- `_recursive_update(original, new_data)`:递归更新配置,支持点号路径,内部方法。
|
|
64
|
+
- `validate_format(_way)`:校验并返回合法格式名,静态方法。
|
|
65
|
+
- `ensure_extension(file)`:确保文件名有正确扩展名。
|
|
66
|
+
|
|
67
|
+
## 三、使用示例
|
|
68
|
+
|
|
69
|
+
### 1. 初始化配置管理器
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from confull import Config
|
|
73
|
+
|
|
74
|
+
# 使用默认参数初始化
|
|
75
|
+
config = Config()
|
|
76
|
+
|
|
77
|
+
# 使用自定义参数初始化
|
|
78
|
+
data = {'a': {'b': 'c'}}
|
|
79
|
+
config = Config(data=data, file='custom_config', way='json')
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### 2. 读取和写入配置项
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
# 写入配置项
|
|
86
|
+
config.write('a.b', 'new_value') # 也可以写为 : config.a.b = 'new_value'
|
|
87
|
+
# 读取配置项
|
|
88
|
+
value = config.read('a.b') # value = config.a.b
|
|
89
|
+
print(value) # 输出: new_value
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### 3. 批量更新配置项
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
new_data = {'a': {'b': 'updated_value'}, 'd': 'e'}
|
|
96
|
+
config.update(new_data)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### 4. 保存和另存配置文件
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
# 保存配置文件
|
|
103
|
+
config.save()
|
|
104
|
+
|
|
105
|
+
# 另存为指定文件和格式
|
|
106
|
+
config.save_to_file(file='backup_config', way='yaml')
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### 5. 删除配置项和清空配置
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
# 删除配置项
|
|
113
|
+
config.del_key('a.b')
|
|
114
|
+
|
|
115
|
+
# 清空配置并删除文件
|
|
116
|
+
config.del_clean()
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### 6.# 读写方法示例
|
|
120
|
+
|
|
121
|
+
```
|
|
122
|
+
# 读写方法示例
|
|
123
|
+
from confull import Config
|
|
124
|
+
|
|
125
|
+
cc = Config()
|
|
126
|
+
cc.write('学校名称', '大学')
|
|
127
|
+
cc.学校.日期 = "2021-01-01"
|
|
128
|
+
print(cc.read('学校.日期'))
|
|
129
|
+
print(cc['学校名称'])
|
|
130
|
+
print(cc.学校.日期)
|
|
131
|
+
print(cc)
|
|
132
|
+
cc.pop('学校名称')
|
|
133
|
+
print(cc)
|
|
134
|
+
cc.clear() # 字典方式清空配置data
|
|
135
|
+
print(cc)
|
|
136
|
+
cc.del_clean()
|
|
137
|
+
|
|
138
|
+
# 字典方式设置值示例
|
|
139
|
+
cc = Config()
|
|
140
|
+
cc.dict = {'地点': '北京', '图书': {'数量': 100, '价格': 10.5}, '学生': {'数量': 1000, '年龄': 20}}
|
|
141
|
+
print(cc)
|
|
142
|
+
cc.del_clean()
|
|
143
|
+
|
|
144
|
+
# 强制覆写示例
|
|
145
|
+
dic_ = {'学校': 'pass'}
|
|
146
|
+
cc = Config(data=dic_)
|
|
147
|
+
cc.write('学校.大学', '大学', overwrite_mode=True) # overwrite_mode=True 强制覆写,但会导致原路径被删除
|
|
148
|
+
print(cc)
|
|
149
|
+
cc.del_clean()
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
## 四、注意事项
|
|
155
|
+
|
|
156
|
+
- 当使用 `write`、`update`、`set_data`、`del_key` 等方法修改配置数据时,若 `auto_save` 为 `True`,会自动保存配置文件。
|
|
157
|
+
- 若配置文件格式不支持,会抛出 `ValueError` 异常。
|
|
158
|
+
- 在使用 `INIConfigHandler` 保存配置时,若数据不是嵌套字典,会将其包装在一个默认的 `'默认'` 节中。
|
|
159
|
+
|
|
160
|
+
## 尾语
|
|
161
|
+
|
|
162
|
+
作者水平有限,尽可能简化配置文件的读写流程,让使用者可以用一种更加直观、便捷的方式去操作配置信息。
|
|
163
|
+
|
|
164
|
+
2024 年 11 月 19 日 zisull@qq.com
|
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# @author: zisull@qq.com
|
|
3
|
+
# @date: 2024年11月19日
|
|
4
|
+
|
|
5
|
+
import configparser
|
|
6
|
+
import os
|
|
7
|
+
import xml.etree.ElementTree as ElementTree
|
|
8
|
+
from collections.abc import MutableMapping
|
|
9
|
+
from threading import Lock
|
|
10
|
+
|
|
11
|
+
import orjson
|
|
12
|
+
import toml
|
|
13
|
+
import yaml
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Config:
|
|
17
|
+
"""
|
|
18
|
+
多格式配置管理器,支持 dict <=> [ini, xml, json, toml, yaml] 的读写与自动保存。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, data: dict = None, file: str = "config", way: str = "toml", replace: bool = False,
|
|
22
|
+
auto_save: bool = True, backup: bool = False):
|
|
23
|
+
"""
|
|
24
|
+
初始化配置管理器。
|
|
25
|
+
:param data: 初始配置数据(dict)
|
|
26
|
+
:param file: 配置文件名(可无扩展名)
|
|
27
|
+
:param way: 配置文件格式(json/toml/yaml/ini/xml)
|
|
28
|
+
:param replace: 是否覆盖已有配置文件
|
|
29
|
+
:param auto_save: 是否自动保存
|
|
30
|
+
:param backup: 是否备份原配置文件
|
|
31
|
+
"""
|
|
32
|
+
self._file = file
|
|
33
|
+
self._way = self.validate_format(way)
|
|
34
|
+
self._file = self.ensure_extension(file)
|
|
35
|
+
self._auto_save = auto_save
|
|
36
|
+
self._data = ConfigNode(data if data is not None else {}, manager=self)
|
|
37
|
+
self._dirty = False if data is not None else True
|
|
38
|
+
self._backup = backup
|
|
39
|
+
self._lock = Lock()
|
|
40
|
+
self._handler = ConfigHandlerFactory.get_handler(self._way)
|
|
41
|
+
|
|
42
|
+
if os.path.exists(self._file) and not replace:
|
|
43
|
+
self._load()
|
|
44
|
+
else:
|
|
45
|
+
# 当文件不存在时,无论replace参数如何都使用data初始化
|
|
46
|
+
if data is not None:
|
|
47
|
+
self._data = ConfigNode(data, manager=self)
|
|
48
|
+
self._dirty = True # 强制标记需要保存
|
|
49
|
+
self.save() # 确保立即保存初始数据
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def json(self) -> str:
|
|
53
|
+
"""以 JSON 字符串格式返回配置数据。"""
|
|
54
|
+
return orjson.dumps(self.dict, option=orjson.OPT_INDENT_2).decode('utf-8')
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def dict(self) -> dict:
|
|
58
|
+
"""以 dict 格式返回配置数据。"""
|
|
59
|
+
return self._data.to_dict()
|
|
60
|
+
|
|
61
|
+
@dict.setter
|
|
62
|
+
def dict(self, value: dict):
|
|
63
|
+
"""用 dict 批量设置配置数据。"""
|
|
64
|
+
self.set_data(value)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def auto_save(self) -> bool:
|
|
68
|
+
"""是否自动保存。"""
|
|
69
|
+
return self._auto_save
|
|
70
|
+
|
|
71
|
+
@auto_save.setter
|
|
72
|
+
def auto_save(self, value: bool):
|
|
73
|
+
"""设置自动保存。"""
|
|
74
|
+
self._auto_save = value
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def backup(self) -> bool:
|
|
78
|
+
"""是否备份原配置文件。"""
|
|
79
|
+
return self._backup
|
|
80
|
+
|
|
81
|
+
@backup.setter
|
|
82
|
+
def backup(self, value: bool):
|
|
83
|
+
"""设置是否备份原配置文件。"""
|
|
84
|
+
self._backup = value
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def str(self) -> str:
|
|
88
|
+
"""以字符串格式返回配置数据。"""
|
|
89
|
+
return str(self.dict)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def file_path(self) -> str:
|
|
93
|
+
"""配置文件路径。"""
|
|
94
|
+
return self._file
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def file_path_abs(self) -> str:
|
|
98
|
+
"""配置文件绝对路径。"""
|
|
99
|
+
return os.path.abspath(self._file)
|
|
100
|
+
|
|
101
|
+
def read(self, key: str, default=None):
|
|
102
|
+
"""
|
|
103
|
+
读取配置项,支持点号路径。
|
|
104
|
+
:param key: 配置项路径(如 a.b.c)
|
|
105
|
+
:param default: 默认值
|
|
106
|
+
"""
|
|
107
|
+
keys = key.split('.')
|
|
108
|
+
node = self._data
|
|
109
|
+
for k in keys:
|
|
110
|
+
if isinstance(node, ConfigNode):
|
|
111
|
+
node = node.data.get(k, None)
|
|
112
|
+
if isinstance(node, dict):
|
|
113
|
+
node = ConfigNode(node, manager=self)
|
|
114
|
+
elif node is None:
|
|
115
|
+
return default
|
|
116
|
+
else:
|
|
117
|
+
return default
|
|
118
|
+
return node
|
|
119
|
+
|
|
120
|
+
def write(self, key: str, value, overwrite_mode: bool = False):
|
|
121
|
+
"""
|
|
122
|
+
写入配置项,支持点号路径。
|
|
123
|
+
:param key: 配置项路径
|
|
124
|
+
:param value: 配置值
|
|
125
|
+
:param overwrite_mode: 路径冲突时是否覆盖
|
|
126
|
+
"""
|
|
127
|
+
self.mark_dirty()
|
|
128
|
+
keys = key.split('.')
|
|
129
|
+
node = self._data
|
|
130
|
+
|
|
131
|
+
for k in keys[:-1]:
|
|
132
|
+
if overwrite_mode:
|
|
133
|
+
if isinstance(node, ConfigNode):
|
|
134
|
+
if k not in node.data or not isinstance(node.data[k], dict):
|
|
135
|
+
node.data[k] = {}
|
|
136
|
+
else:
|
|
137
|
+
node.data = {k: {}}
|
|
138
|
+
node = node[k]
|
|
139
|
+
else:
|
|
140
|
+
node = getattr(node, k)
|
|
141
|
+
|
|
142
|
+
setattr(node, keys[-1], value)
|
|
143
|
+
|
|
144
|
+
if self.auto_save:
|
|
145
|
+
self.save()
|
|
146
|
+
|
|
147
|
+
def del_clean(self):
|
|
148
|
+
"""清空所有配置并删除配置文件。"""
|
|
149
|
+
self.mark_dirty()
|
|
150
|
+
with self._lock:
|
|
151
|
+
if os.path.exists(self._file):
|
|
152
|
+
try:
|
|
153
|
+
os.remove(self._file)
|
|
154
|
+
self._data = ConfigNode({}, manager=self)
|
|
155
|
+
return True
|
|
156
|
+
except OSError as e:
|
|
157
|
+
print(f"清除配置文件 {self._file} 失败:{e}")
|
|
158
|
+
else:
|
|
159
|
+
print(f"配置文件 {self._file} 不存在,无法清除")
|
|
160
|
+
return False
|
|
161
|
+
|
|
162
|
+
def update(self, data: dict):
|
|
163
|
+
"""
|
|
164
|
+
批量更新配置项。
|
|
165
|
+
:param data: dict,支持点号路径
|
|
166
|
+
"""
|
|
167
|
+
self.mark_dirty()
|
|
168
|
+
self._recursive_update(self._data.data, data)
|
|
169
|
+
if self.auto_save:
|
|
170
|
+
self.save()
|
|
171
|
+
|
|
172
|
+
def set_data(self, data: dict):
|
|
173
|
+
"""
|
|
174
|
+
用 dict 完全替换配置数据。
|
|
175
|
+
:param data: 新配置 dict
|
|
176
|
+
"""
|
|
177
|
+
self.mark_dirty()
|
|
178
|
+
self._data = ConfigNode(data, manager=self)
|
|
179
|
+
if self.auto_save:
|
|
180
|
+
self.save()
|
|
181
|
+
|
|
182
|
+
def del_key(self, key: str):
|
|
183
|
+
"""
|
|
184
|
+
删除指定配置项,支持点号路径。
|
|
185
|
+
:param key: 配置项路径
|
|
186
|
+
"""
|
|
187
|
+
self.mark_dirty()
|
|
188
|
+
keys = key.split('.')
|
|
189
|
+
if not keys:
|
|
190
|
+
return
|
|
191
|
+
node = self._data
|
|
192
|
+
parent_nodes = []
|
|
193
|
+
for k in keys[:-1]:
|
|
194
|
+
parent_nodes.append((node, k))
|
|
195
|
+
node = getattr(node, k, None)
|
|
196
|
+
if node is None:
|
|
197
|
+
return
|
|
198
|
+
final_key = keys[-1]
|
|
199
|
+
if final_key in node.data:
|
|
200
|
+
del node.data[final_key]
|
|
201
|
+
while parent_nodes:
|
|
202
|
+
parent, key_in_parent = parent_nodes.pop()
|
|
203
|
+
if not parent[key_in_parent].data:
|
|
204
|
+
del parent[key_in_parent]
|
|
205
|
+
else:
|
|
206
|
+
break
|
|
207
|
+
if self.auto_save:
|
|
208
|
+
self.save()
|
|
209
|
+
|
|
210
|
+
def _load(self):
|
|
211
|
+
"""从文件加载配置。"""
|
|
212
|
+
with self._lock:
|
|
213
|
+
try:
|
|
214
|
+
with open(self._file, 'rb' if self._way == "json" else 'r',
|
|
215
|
+
encoding=None if self._way == "json" else 'utf-8') as f:
|
|
216
|
+
raw_data = self._handler.load(f)
|
|
217
|
+
self._data = ConfigNode(raw_data, manager=self)
|
|
218
|
+
except Exception as e:
|
|
219
|
+
print(f"加载配置文件 {self._file} 失败:{e}")
|
|
220
|
+
|
|
221
|
+
def load(self, file: str = None, way: str = None):
|
|
222
|
+
"""
|
|
223
|
+
切换配置文件或格式(不自动加载内容)。
|
|
224
|
+
:param file: 新文件名
|
|
225
|
+
:param way: 新格式
|
|
226
|
+
"""
|
|
227
|
+
if file:
|
|
228
|
+
self._file = file
|
|
229
|
+
if way:
|
|
230
|
+
self._way = way.lower()
|
|
231
|
+
self._handler = ConfigHandlerFactory.get_handler(self._way)
|
|
232
|
+
|
|
233
|
+
def mark_dirty(self):
|
|
234
|
+
"""标记配置已更改。"""
|
|
235
|
+
self._dirty = True
|
|
236
|
+
|
|
237
|
+
def save(self):
|
|
238
|
+
"""保存配置到文件。"""
|
|
239
|
+
with self._lock:
|
|
240
|
+
if not self._dirty:
|
|
241
|
+
return
|
|
242
|
+
try:
|
|
243
|
+
self._backup_file()
|
|
244
|
+
self._ensure_file_exists()
|
|
245
|
+
# 修复:为 XML 格式添加二进制写入模式
|
|
246
|
+
with open(self._file, 'wb' if self._way in ["json", "xml"] else 'w',
|
|
247
|
+
encoding=None if self._way in ["json", "xml"] else 'utf-8') as f:
|
|
248
|
+
self._handler.save(self._data.to_dict(), f)
|
|
249
|
+
self._dirty = False
|
|
250
|
+
except Exception as e:
|
|
251
|
+
print(f"保存配置文件失败 {self._file}: {e}")
|
|
252
|
+
|
|
253
|
+
def save_to_file(self, file: str = None, way: str = None):
|
|
254
|
+
"""
|
|
255
|
+
另存为指定文件和格式。
|
|
256
|
+
:param file: 目标文件
|
|
257
|
+
:param way: 目标格式
|
|
258
|
+
"""
|
|
259
|
+
with self._lock:
|
|
260
|
+
try:
|
|
261
|
+
# 使用局部变量来存储文件路径和格式
|
|
262
|
+
target_file = self.ensure_extension(file) if file else self._file
|
|
263
|
+
target_way = self.validate_format(way) if way else self._way
|
|
264
|
+
target_handler = ConfigHandlerFactory.get_handler(target_way)
|
|
265
|
+
|
|
266
|
+
# 确保文件存在
|
|
267
|
+
self._ensure_file_exists()
|
|
268
|
+
|
|
269
|
+
# 打开文件并保存数据
|
|
270
|
+
with open(target_file, 'wb' if target_way == "json" else 'w',
|
|
271
|
+
encoding=None if target_way == "json" else 'utf-8') as f:
|
|
272
|
+
target_handler.save(self._data.to_dict(), f)
|
|
273
|
+
|
|
274
|
+
print(f"配置已成功另存到 {target_file}")
|
|
275
|
+
except Exception as e:
|
|
276
|
+
print(f"另存配置文件失败 {target_file}: {e}")
|
|
277
|
+
|
|
278
|
+
def _ensure_file_exists(self):
|
|
279
|
+
"""确保配置文件存在。"""
|
|
280
|
+
if not os.path.exists(self._file):
|
|
281
|
+
with open(self._file, 'w'):
|
|
282
|
+
pass # 创建一个空文件
|
|
283
|
+
|
|
284
|
+
def _backup_file(self):
|
|
285
|
+
"""备份原配置文件。"""
|
|
286
|
+
if os.path.exists(self._file) and self.backup:
|
|
287
|
+
backup_file = self._file + '.bak'
|
|
288
|
+
try:
|
|
289
|
+
os.replace(self._file, backup_file)
|
|
290
|
+
except Exception as e:
|
|
291
|
+
print(f"备份文件失败: {e}")
|
|
292
|
+
|
|
293
|
+
def _recursive_update(self, original, new_data):
|
|
294
|
+
"""
|
|
295
|
+
递归更新配置,支持点号路径。
|
|
296
|
+
:param original: 原始 dict
|
|
297
|
+
:param new_data: 新数据 dict
|
|
298
|
+
"""
|
|
299
|
+
for key, value in new_data.items():
|
|
300
|
+
if '.' in key:
|
|
301
|
+
keys = key.split('.')
|
|
302
|
+
current = original
|
|
303
|
+
for k in keys[:-1]:
|
|
304
|
+
current = current.setdefault(k, {})
|
|
305
|
+
current[keys[-1]] = value
|
|
306
|
+
elif isinstance(value, dict) and isinstance(original.get(key, None), dict):
|
|
307
|
+
self._recursive_update(original[key], value)
|
|
308
|
+
else:
|
|
309
|
+
if original.get(key) != value:
|
|
310
|
+
original[key] = value
|
|
311
|
+
self.mark_dirty()
|
|
312
|
+
|
|
313
|
+
@staticmethod
|
|
314
|
+
def validate_format(_way):
|
|
315
|
+
"""
|
|
316
|
+
校验并返回合法格式名。
|
|
317
|
+
:param _way: 格式名
|
|
318
|
+
"""
|
|
319
|
+
_way = _way.lower()
|
|
320
|
+
way_list = ['json', 'toml', 'yaml', 'ini', 'xml'] # 修复:将 way_list 定义为局部变量
|
|
321
|
+
if _way not in way_list:
|
|
322
|
+
raise ValueError(f"Unsupported format: {_way}. Supported formats are: {', '.join(way_list)}")
|
|
323
|
+
return _way
|
|
324
|
+
|
|
325
|
+
def ensure_extension(self, file):
|
|
326
|
+
"""
|
|
327
|
+
确保文件名有正确扩展名。
|
|
328
|
+
:param file: 文件名
|
|
329
|
+
"""
|
|
330
|
+
if not os.path.splitext(file)[1]:
|
|
331
|
+
file += f".{self._way}"
|
|
332
|
+
return file
|
|
333
|
+
|
|
334
|
+
def __str__(self):
|
|
335
|
+
"""str(self)"""
|
|
336
|
+
return str(self.dict)
|
|
337
|
+
|
|
338
|
+
def __repr__(self):
|
|
339
|
+
"""repr(self)"""
|
|
340
|
+
return repr(self.dict)
|
|
341
|
+
|
|
342
|
+
def __getattr__(self, item: str):
|
|
343
|
+
"""属性访问代理到配置数据。"""
|
|
344
|
+
return getattr(self._data, item)
|
|
345
|
+
|
|
346
|
+
def __getitem__(self, item: str):
|
|
347
|
+
"""dict 方式访问配置数据。"""
|
|
348
|
+
return self._data[item]
|
|
349
|
+
|
|
350
|
+
def __call__(self, key: str, value=None):
|
|
351
|
+
"""cc(key) 等价于 cc.read(key, value)"""
|
|
352
|
+
return self.read(key, value)
|
|
353
|
+
|
|
354
|
+
def __len__(self):
|
|
355
|
+
"""配置项数量。"""
|
|
356
|
+
return len(self._data)
|
|
357
|
+
|
|
358
|
+
def __iter__(self):
|
|
359
|
+
"""遍历配置项。"""
|
|
360
|
+
return iter(self._data)
|
|
361
|
+
|
|
362
|
+
def __contains__(self, item):
|
|
363
|
+
"""判断配置项是否存在。"""
|
|
364
|
+
return item in self._data
|
|
365
|
+
|
|
366
|
+
def __bool__(self):
|
|
367
|
+
"""配置是否非空。"""
|
|
368
|
+
return bool(self._data)
|
|
369
|
+
|
|
370
|
+
def __enter__(self):
|
|
371
|
+
"""上下文管理器 enter。"""
|
|
372
|
+
return self
|
|
373
|
+
|
|
374
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
375
|
+
"""上下文管理器 exit,自动保存。"""
|
|
376
|
+
self.save()
|
|
377
|
+
|
|
378
|
+
def __setattr__(self, key, value):
|
|
379
|
+
"""属性赋值代理到配置数据,内部属性用 _ 前缀。"""
|
|
380
|
+
if key.startswith('_'):
|
|
381
|
+
super().__setattr__(key, value)
|
|
382
|
+
else:
|
|
383
|
+
setattr(self._data, key, value)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class ConfigHandler:
|
|
387
|
+
"""
|
|
388
|
+
配置文件处理器基类。
|
|
389
|
+
"""
|
|
390
|
+
def load(self, file):
|
|
391
|
+
"""加载配置文件。"""
|
|
392
|
+
raise NotImplementedError
|
|
393
|
+
|
|
394
|
+
def save(self, data, file):
|
|
395
|
+
"""保存配置文件。"""
|
|
396
|
+
raise NotImplementedError
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
class JSONConfigHandler(ConfigHandler):
|
|
400
|
+
"""
|
|
401
|
+
JSON 配置文件处理器。
|
|
402
|
+
"""
|
|
403
|
+
def load(self, file):
|
|
404
|
+
"""加载 JSON 配置。"""
|
|
405
|
+
return orjson.loads(file.read())
|
|
406
|
+
|
|
407
|
+
def save(self, data, file):
|
|
408
|
+
"""保存 JSON 配置。"""
|
|
409
|
+
file.write(orjson.dumps(data, option=orjson.OPT_INDENT_2))
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
class TOMLConfigHandler(ConfigHandler):
|
|
413
|
+
"""
|
|
414
|
+
TOML 配置文件处理器。
|
|
415
|
+
"""
|
|
416
|
+
def load(self, file):
|
|
417
|
+
"""加载 TOML 配置。"""
|
|
418
|
+
return toml.load(file)
|
|
419
|
+
|
|
420
|
+
def save(self, data, file):
|
|
421
|
+
"""保存 TOML 配置。"""
|
|
422
|
+
file.write(toml.dumps(data))
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
class YAMLConfigHandler(ConfigHandler):
|
|
426
|
+
"""
|
|
427
|
+
YAML 配置文件处理器。
|
|
428
|
+
"""
|
|
429
|
+
def load(self, file):
|
|
430
|
+
"""加载 YAML 配置。"""
|
|
431
|
+
return yaml.safe_load(file)
|
|
432
|
+
|
|
433
|
+
def save(self, data, file):
|
|
434
|
+
"""保存 YAML 配置。"""
|
|
435
|
+
yaml.dump(data, file, allow_unicode=True)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
class INIConfigHandler(ConfigHandler):
|
|
439
|
+
"""
|
|
440
|
+
INI 配置文件处理器。
|
|
441
|
+
"""
|
|
442
|
+
def load(self, file):
|
|
443
|
+
"""加载 INI 配置。"""
|
|
444
|
+
config = configparser.ConfigParser()
|
|
445
|
+
config.read_file(file)
|
|
446
|
+
return {s: dict(config.items(s)) for s in config.sections()}
|
|
447
|
+
|
|
448
|
+
def save(self, data, file):
|
|
449
|
+
"""保存 INI 配置。"""
|
|
450
|
+
config = configparser.ConfigParser()
|
|
451
|
+
# 如果 data 不是嵌套字典,包装在一个默认的 section 中
|
|
452
|
+
if not all(isinstance(v, dict) for v in data.values()):
|
|
453
|
+
data = {'默认': data}
|
|
454
|
+
config.read_dict(data)
|
|
455
|
+
config.write(file)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
class XMLConfigHandler(ConfigHandler):
|
|
459
|
+
"""
|
|
460
|
+
XML 配置文件处理器。
|
|
461
|
+
"""
|
|
462
|
+
def load(self, file):
|
|
463
|
+
"""加载 XML 配置。"""
|
|
464
|
+
tree = ElementTree.parse(file)
|
|
465
|
+
root = tree.getroot()
|
|
466
|
+
return self._element_to_dict(root)
|
|
467
|
+
|
|
468
|
+
def save(self, data, file):
|
|
469
|
+
"""保存 XML 配置。"""
|
|
470
|
+
root = self._dict_to_element('config', data)
|
|
471
|
+
tree = ElementTree.ElementTree(root)
|
|
472
|
+
tree.write(file, encoding='utf-8', xml_declaration=True)
|
|
473
|
+
|
|
474
|
+
def _element_to_dict(self, element):
|
|
475
|
+
"""递归解析 XML 元素为 dict。"""
|
|
476
|
+
data = {}
|
|
477
|
+
for child in element:
|
|
478
|
+
if len(child):
|
|
479
|
+
data[child.tag] = self._element_to_dict(child)
|
|
480
|
+
else:
|
|
481
|
+
data[child.tag] = child.text
|
|
482
|
+
return data
|
|
483
|
+
|
|
484
|
+
def _dict_to_element(self, tag, data):
|
|
485
|
+
"""递归将 dict 转为 XML 元素。"""
|
|
486
|
+
element = ElementTree.Element(tag)
|
|
487
|
+
for key, value in data.items():
|
|
488
|
+
if isinstance(value, dict):
|
|
489
|
+
child = self._dict_to_element(key, value)
|
|
490
|
+
else:
|
|
491
|
+
child = ElementTree.Element(key)
|
|
492
|
+
child.text = str(value)
|
|
493
|
+
element.append(child)
|
|
494
|
+
return element
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
class ConfigHandlerFactory:
|
|
498
|
+
handlers = {
|
|
499
|
+
'json': JSONConfigHandler(),
|
|
500
|
+
'toml': TOMLConfigHandler(),
|
|
501
|
+
'yaml': YAMLConfigHandler(),
|
|
502
|
+
'ini': INIConfigHandler(),
|
|
503
|
+
'xml': XMLConfigHandler(), # Added XML handler
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
@staticmethod
|
|
507
|
+
def get_handler(_format):
|
|
508
|
+
handler = ConfigHandlerFactory.handlers.get(_format)
|
|
509
|
+
if not handler:
|
|
510
|
+
raise ValueError(f"Unsupported format: {_format}")
|
|
511
|
+
return handler
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
class ConfigNode(MutableMapping):
|
|
515
|
+
"""
|
|
516
|
+
配置节点,支持嵌套字典结构与自动保存。
|
|
517
|
+
"""
|
|
518
|
+
|
|
519
|
+
def __init__(self, data=None, manager=None, parent=None, key_in_parent=None):
|
|
520
|
+
"""
|
|
521
|
+
初始化配置节点。
|
|
522
|
+
:param data: 节点数据(dict)
|
|
523
|
+
:param manager: 顶层 Config 实例
|
|
524
|
+
:param parent: 父节点
|
|
525
|
+
:param key_in_parent: 在父节点中的键名
|
|
526
|
+
"""
|
|
527
|
+
self._data = data if data is not None else {}
|
|
528
|
+
self._manager = manager
|
|
529
|
+
self._parent = parent
|
|
530
|
+
self._key_in_parent = key_in_parent
|
|
531
|
+
|
|
532
|
+
@property
|
|
533
|
+
def data(self):
|
|
534
|
+
"""节点数据(dict)。"""
|
|
535
|
+
return self._data
|
|
536
|
+
|
|
537
|
+
@data.setter
|
|
538
|
+
def data(self, value):
|
|
539
|
+
"""设置节点数据并自动保存。"""
|
|
540
|
+
self._data = value
|
|
541
|
+
self._trigger_save()
|
|
542
|
+
|
|
543
|
+
def _trigger_save(self):
|
|
544
|
+
"""触发自动保存。"""
|
|
545
|
+
if self._manager:
|
|
546
|
+
self._manager.mark_dirty()
|
|
547
|
+
if self._manager.auto_save:
|
|
548
|
+
self._manager.save()
|
|
549
|
+
|
|
550
|
+
def __getitem__(self, key):
|
|
551
|
+
"""获取子项或子节点。"""
|
|
552
|
+
value = self._data.get(key)
|
|
553
|
+
if isinstance(value, dict):
|
|
554
|
+
return ConfigNode(value, manager=self._manager, parent=self, key_in_parent=key)
|
|
555
|
+
elif value is not None:
|
|
556
|
+
return value
|
|
557
|
+
else:
|
|
558
|
+
raise KeyError(f"Key '{key}' not found.")
|
|
559
|
+
|
|
560
|
+
def __setitem__(self, key, value):
|
|
561
|
+
"""设置子项并自动保存。"""
|
|
562
|
+
self._data[key] = value
|
|
563
|
+
self._trigger_save()
|
|
564
|
+
|
|
565
|
+
def __delitem__(self, key):
|
|
566
|
+
"""删除子项并自动保存。"""
|
|
567
|
+
if key in self._data:
|
|
568
|
+
del self._data[key]
|
|
569
|
+
self._trigger_save()
|
|
570
|
+
else:
|
|
571
|
+
raise KeyError(f"Key '{key}' not found.")
|
|
572
|
+
|
|
573
|
+
def __iter__(self):
|
|
574
|
+
"""遍历所有子项。"""
|
|
575
|
+
return iter(self._data)
|
|
576
|
+
|
|
577
|
+
def __len__(self):
|
|
578
|
+
"""子项数量。"""
|
|
579
|
+
return len(self._data)
|
|
580
|
+
|
|
581
|
+
def __getattr__(self, key):
|
|
582
|
+
"""属性方式访问子项。"""
|
|
583
|
+
if key in self._data:
|
|
584
|
+
value = self._data[key]
|
|
585
|
+
if isinstance(value, dict):
|
|
586
|
+
return ConfigNode(value, manager=self._manager, parent=self, key_in_parent=key)
|
|
587
|
+
else:
|
|
588
|
+
return value
|
|
589
|
+
else:
|
|
590
|
+
self._data[key] = {}
|
|
591
|
+
return ConfigNode(self._data[key], manager=self._manager, key_in_parent=key)
|
|
592
|
+
|
|
593
|
+
def __setattr__(self, key, value):
|
|
594
|
+
"""属性方式设置子项,内部变量用 _ 前缀。"""
|
|
595
|
+
if key.startswith('_'):
|
|
596
|
+
super().__setattr__(key, value)
|
|
597
|
+
else:
|
|
598
|
+
self._data[key] = value
|
|
599
|
+
# 递归找到最顶层的 manager 并触发保存
|
|
600
|
+
node = self
|
|
601
|
+
while hasattr(node, '_parent') and node._parent is not None:
|
|
602
|
+
node = node._parent
|
|
603
|
+
if hasattr(node, '_manager') and node._manager is not None:
|
|
604
|
+
node._manager.mark_dirty()
|
|
605
|
+
if node._manager.auto_save:
|
|
606
|
+
node._manager.save()
|
|
607
|
+
|
|
608
|
+
def to_dict(self):
|
|
609
|
+
"""递归转为 dict。"""
|
|
610
|
+
return {key: (value.to_dict() if isinstance(value, ConfigNode) else value)
|
|
611
|
+
for key, value in self._data.items()}
|
|
612
|
+
|
|
613
|
+
def __repr__(self):
|
|
614
|
+
"""repr(self)"""
|
|
615
|
+
return repr(self.to_dict())
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
if __name__ == "__main__":
|
|
619
|
+
pass
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "confull"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = "一个简单的配置管理工具(A simple dictionary configuration management tool),dict <-> config file [json, toml, yaml, ini, xml]"
|
|
5
|
+
authors = ["zisul <zisull@qq.com>"]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
packages = [{ include = "confull" }]
|
|
8
|
+
|
|
9
|
+
[tool.poetry.dependencies]
|
|
10
|
+
python = "^3.6"
|
|
11
|
+
orjson = "^3.10.11"
|
|
12
|
+
toml = "^0.10.2"
|
|
13
|
+
pyyaml = "^6.0.2"
|
|
14
|
+
configparser = "^7.1.0"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["poetry-core>=1.0.0"]
|
|
19
|
+
build-backend = "poetry.core.masonry.api"
|