mdbq 4.0.20__py3-none-any.whl → 4.0.22__py3-none-any.whl
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.
- mdbq/__version__.py +1 -1
- mdbq/myconf/myconf2.py +620 -0
- {mdbq-4.0.20.dist-info → mdbq-4.0.22.dist-info}/METADATA +1 -1
- {mdbq-4.0.20.dist-info → mdbq-4.0.22.dist-info}/RECORD +6 -5
- {mdbq-4.0.20.dist-info → mdbq-4.0.22.dist-info}/WHEEL +0 -0
- {mdbq-4.0.20.dist-info → mdbq-4.0.22.dist-info}/top_level.txt +0 -0
mdbq/__version__.py
CHANGED
@@ -1 +1 @@
|
|
1
|
-
VERSION = '4.0.
|
1
|
+
VERSION = '4.0.22'
|
mdbq/myconf/myconf2.py
ADDED
@@ -0,0 +1,620 @@
|
|
1
|
+
import re
|
2
|
+
from typing import Dict, Any, Optional, Union, List, Tuple, Type, TypeVar
|
3
|
+
from pathlib import Path
|
4
|
+
from mdbq.log import mylogger
|
5
|
+
from dataclasses import dataclass, field
|
6
|
+
from enum import Enum
|
7
|
+
import time
|
8
|
+
|
9
|
+
logger = mylogger.MyLogger(
|
10
|
+
logging_mode='both',
|
11
|
+
log_level='info',
|
12
|
+
log_format='json',
|
13
|
+
max_log_size=50,
|
14
|
+
backup_count=5,
|
15
|
+
enable_async=False, # 是否启用异步日志
|
16
|
+
sample_rate=1, # 采样DEBUG/INFO日志
|
17
|
+
sensitive_fields=[], # 敏感字段过滤
|
18
|
+
enable_metrics=False, # 是否启用性能指标
|
19
|
+
)
|
20
|
+
|
21
|
+
T = TypeVar('T') # 类型变量
|
22
|
+
|
23
|
+
|
24
|
+
class ConfigError(Exception):
|
25
|
+
"""配置相关的基础异常类"""
|
26
|
+
def __init__(self, message: str, file_path: Optional[Union[str, Path]] = None,
|
27
|
+
section: Optional[str] = None, key: Optional[str] = None):
|
28
|
+
self.message = message
|
29
|
+
self.file_path = str(file_path) if file_path else None
|
30
|
+
self.section = section
|
31
|
+
self.key = key
|
32
|
+
super().__init__(self._format_message())
|
33
|
+
|
34
|
+
def _format_message(self) -> str:
|
35
|
+
"""格式化错误消息"""
|
36
|
+
parts = [self.message]
|
37
|
+
if self.file_path:
|
38
|
+
parts.append(f"文件: {self.file_path}")
|
39
|
+
if self.section:
|
40
|
+
parts.append(f"节: [{self.section}]")
|
41
|
+
if self.key:
|
42
|
+
parts.append(f"键: {self.key}")
|
43
|
+
return " | ".join(parts)
|
44
|
+
|
45
|
+
|
46
|
+
class ConfigFileNotFoundError(ConfigError):
|
47
|
+
"""配置文件不存在异常"""
|
48
|
+
def __init__(self, file_path: Union[str, Path]):
|
49
|
+
super().__init__("配置文件不存在", file_path=file_path)
|
50
|
+
|
51
|
+
|
52
|
+
class ConfigReadError(ConfigError):
|
53
|
+
"""读取配置文件失败异常"""
|
54
|
+
def __init__(self, file_path: Union[str, Path], original_error: Exception):
|
55
|
+
super().__init__(
|
56
|
+
f"读取配置文件失败: {str(original_error)}",
|
57
|
+
file_path=file_path
|
58
|
+
)
|
59
|
+
self.original_error = original_error
|
60
|
+
|
61
|
+
|
62
|
+
class ConfigWriteError(ConfigError):
|
63
|
+
"""写入配置文件失败异常"""
|
64
|
+
def __init__(self, file_path: Union[str, Path], original_error: Exception):
|
65
|
+
super().__init__(
|
66
|
+
f"写入配置文件失败: {str(original_error)}",
|
67
|
+
file_path=file_path
|
68
|
+
)
|
69
|
+
self.original_error = original_error
|
70
|
+
|
71
|
+
|
72
|
+
class ConfigValueError(ConfigError):
|
73
|
+
"""配置值无效异常"""
|
74
|
+
def __init__(self, message: str, file_path: Union[str, Path],
|
75
|
+
section: Optional[str] = None, key: Optional[str] = None):
|
76
|
+
super().__init__(message, file_path=file_path, section=section, key=key)
|
77
|
+
|
78
|
+
|
79
|
+
class ConfigSectionNotFoundError(ConfigError):
|
80
|
+
"""配置节不存在异常"""
|
81
|
+
def __init__(self, file_path: Union[str, Path], section: str):
|
82
|
+
super().__init__(
|
83
|
+
f"配置节不存在",
|
84
|
+
file_path=file_path,
|
85
|
+
section=section
|
86
|
+
)
|
87
|
+
|
88
|
+
|
89
|
+
class ConfigKeyNotFoundError(ConfigError):
|
90
|
+
"""配置键不存在异常"""
|
91
|
+
def __init__(self, file_path: Union[str, Path], section: str, key: str):
|
92
|
+
super().__init__(
|
93
|
+
f"配置键不存在",
|
94
|
+
file_path=file_path,
|
95
|
+
section=section,
|
96
|
+
key=key
|
97
|
+
)
|
98
|
+
|
99
|
+
|
100
|
+
class CommentStyle(Enum):
|
101
|
+
"""配置文件支持的注释风格"""
|
102
|
+
HASH = '#' # Python风格注释
|
103
|
+
DOUBLE_SLASH = '//' # C风格注释
|
104
|
+
SEMICOLON = ';' # INI风格注释
|
105
|
+
|
106
|
+
|
107
|
+
@dataclass
|
108
|
+
class ConfigOptions:
|
109
|
+
"""配置解析器选项"""
|
110
|
+
comment_styles: List[CommentStyle] = field(default_factory=lambda: [CommentStyle.HASH, CommentStyle.DOUBLE_SLASH])
|
111
|
+
encoding: str = 'utf-8'
|
112
|
+
auto_create: bool = False
|
113
|
+
strip_values: bool = True
|
114
|
+
preserve_comments: bool = True
|
115
|
+
default_section: str = 'DEFAULT'
|
116
|
+
separators: List[str] = field(default_factory=lambda: ['=', ':', ':'])
|
117
|
+
cache_ttl: int = 300 # 5分钟缓存过期
|
118
|
+
validate_keys: bool = True
|
119
|
+
key_pattern: str = r'^[a-zA-Z0-9_\-\.]+$'
|
120
|
+
case_sensitive: bool = False
|
121
|
+
|
122
|
+
|
123
|
+
class ConfigParser:
|
124
|
+
"""配置文件解析器"""
|
125
|
+
|
126
|
+
def __init__(self, options: Optional[ConfigOptions] = None):
|
127
|
+
self.options = options or ConfigOptions()
|
128
|
+
self._config_cache: Dict[str, Dict[str, Any]] = {}
|
129
|
+
self._cache_timestamps: Dict[str, float] = {}
|
130
|
+
self._comments_cache: Dict[str, Dict[str, List[str]]] = {}
|
131
|
+
self._section_map: Dict[str, Dict[str, str]] = {}
|
132
|
+
self._current_file: Optional[Path] = None
|
133
|
+
|
134
|
+
def __enter__(self) -> 'ConfigParser':
|
135
|
+
return self
|
136
|
+
|
137
|
+
def __exit__(self, exc_type: Optional[Type[BaseException]],
|
138
|
+
exc_val: Optional[BaseException],
|
139
|
+
exc_tb: Optional[Any]) -> None:
|
140
|
+
self._current_file = None
|
141
|
+
|
142
|
+
def open(self, file_path: Union[str, Path]) -> 'ConfigParser':
|
143
|
+
"""打开配置文件"""
|
144
|
+
file_path = Path(file_path)
|
145
|
+
if not file_path.exists() and not self.options.auto_create:
|
146
|
+
raise ConfigFileNotFoundError(file_path)
|
147
|
+
self._current_file = file_path
|
148
|
+
return self
|
149
|
+
|
150
|
+
def _ensure_file_open(self) -> None:
|
151
|
+
"""确保文件已打开"""
|
152
|
+
if self._current_file is None:
|
153
|
+
raise ConfigError("未打开任何配置文件,请先调用 open() 方法")
|
154
|
+
|
155
|
+
def _is_comment_line(self, line: str) -> bool:
|
156
|
+
"""判断是否为注释行"""
|
157
|
+
stripped = line.strip()
|
158
|
+
return any(stripped.startswith(style.value) for style in self.options.comment_styles)
|
159
|
+
|
160
|
+
def _extract_comment(self, line: str) -> Tuple[str, str]:
|
161
|
+
"""从行中提取注释"""
|
162
|
+
for style in self.options.comment_styles:
|
163
|
+
comment_match = re.search(fr'\s+{re.escape(style.value)}.*$', line)
|
164
|
+
if comment_match:
|
165
|
+
return line[:comment_match.start()].strip(), comment_match.group(0)
|
166
|
+
return line.strip(), ''
|
167
|
+
|
168
|
+
def _split_key_value(self, line: str) -> Optional[Tuple[str, str]]:
|
169
|
+
"""分割配置行为键值对"""
|
170
|
+
for sep in self.options.separators:
|
171
|
+
if sep in line:
|
172
|
+
key_part, value_part = line.split(sep, 1)
|
173
|
+
return key_part.strip(), value_part
|
174
|
+
|
175
|
+
for sep in [':', ':']:
|
176
|
+
if sep in line:
|
177
|
+
pattern = fr'\s*{re.escape(sep)}\s*'
|
178
|
+
parts = re.split(pattern, line, 1)
|
179
|
+
if len(parts) == 2:
|
180
|
+
return parts[0].strip(), parts[1]
|
181
|
+
|
182
|
+
return None
|
183
|
+
|
184
|
+
def _validate_key(self, key: str) -> bool:
|
185
|
+
"""验证键名是否合法"""
|
186
|
+
if not self.options.validate_keys:
|
187
|
+
return True
|
188
|
+
return bool(re.match(self.options.key_pattern, key))
|
189
|
+
|
190
|
+
def _get_cached_config(self, file_path: str) -> Optional[Dict[str, Any]]:
|
191
|
+
"""获取缓存的配置"""
|
192
|
+
if file_path not in self._config_cache or file_path not in self._cache_timestamps:
|
193
|
+
return None
|
194
|
+
|
195
|
+
if time.time() - self._cache_timestamps[file_path] > self.options.cache_ttl:
|
196
|
+
return None
|
197
|
+
|
198
|
+
return self._config_cache[file_path]
|
199
|
+
|
200
|
+
def _update_cache(self, file_path: str, config: Dict[str, Any]) -> None:
|
201
|
+
"""更新配置缓存"""
|
202
|
+
self._config_cache[file_path] = config
|
203
|
+
self._cache_timestamps[file_path] = time.time()
|
204
|
+
|
205
|
+
def _normalize_section(self, section: str) -> str:
|
206
|
+
"""标准化节名称"""
|
207
|
+
return section if self.options.case_sensitive else section.lower()
|
208
|
+
|
209
|
+
def _get_original_section(self, file_path: str, normalized_section: str) -> Optional[str]:
|
210
|
+
"""获取原始节名称"""
|
211
|
+
if self.options.case_sensitive:
|
212
|
+
return normalized_section
|
213
|
+
return self._section_map.get(file_path, {}).get(normalized_section)
|
214
|
+
|
215
|
+
def _update_section_map(self, file_path: str, section: str) -> None:
|
216
|
+
"""更新节名称映射"""
|
217
|
+
if not self.options.case_sensitive:
|
218
|
+
normalized = self._normalize_section(section)
|
219
|
+
if file_path not in self._section_map:
|
220
|
+
self._section_map[file_path] = {}
|
221
|
+
self._section_map[file_path][normalized] = section
|
222
|
+
|
223
|
+
def _clear_cache(self, file_path: Optional[str] = None) -> None:
|
224
|
+
"""清除配置缓存"""
|
225
|
+
if file_path:
|
226
|
+
self._config_cache.pop(file_path, None)
|
227
|
+
self._cache_timestamps.pop(file_path, None)
|
228
|
+
self._comments_cache.pop(file_path, None)
|
229
|
+
self._section_map.pop(file_path, None)
|
230
|
+
else:
|
231
|
+
self._config_cache.clear()
|
232
|
+
self._cache_timestamps.clear()
|
233
|
+
self._comments_cache.clear()
|
234
|
+
self._section_map.clear()
|
235
|
+
|
236
|
+
def _convert_value(self, value: str, target_type: Type[T]) -> T:
|
237
|
+
"""转换配置值到指定类型"""
|
238
|
+
try:
|
239
|
+
if target_type == bool:
|
240
|
+
return bool(value.lower() in ('true', 'yes', '1', 'on'))
|
241
|
+
elif target_type == list:
|
242
|
+
if not value.strip():
|
243
|
+
return []
|
244
|
+
for sep in [',', ';', '|', ' ']:
|
245
|
+
if sep in value:
|
246
|
+
return [item.strip() for item in value.split(sep) if item.strip()]
|
247
|
+
return [value.strip()]
|
248
|
+
elif target_type == tuple:
|
249
|
+
if not value.strip():
|
250
|
+
return ()
|
251
|
+
for sep in [',', ';', '|', ' ']:
|
252
|
+
if sep in value:
|
253
|
+
return tuple(item.strip() for item in value.split(sep) if item.strip())
|
254
|
+
return (value.strip(),)
|
255
|
+
elif target_type == set:
|
256
|
+
if not value.strip():
|
257
|
+
return set()
|
258
|
+
for sep in [',', ';', '|', ' ']:
|
259
|
+
if sep in value:
|
260
|
+
return {item.strip() for item in value.split(sep) if item.strip()}
|
261
|
+
return {value.strip()}
|
262
|
+
elif target_type == dict:
|
263
|
+
if not value.strip():
|
264
|
+
return {}
|
265
|
+
result = {}
|
266
|
+
for sep in [',', ';', '|']:
|
267
|
+
if sep in value:
|
268
|
+
pairs = [pair.strip() for pair in value.split(sep) if pair.strip()]
|
269
|
+
for pair in pairs:
|
270
|
+
if '=' in pair:
|
271
|
+
key, val = pair.split('=', 1)
|
272
|
+
result[key.strip()] = val.strip()
|
273
|
+
return result
|
274
|
+
if '=' in value:
|
275
|
+
key, val = value.split('=', 1)
|
276
|
+
return {key.strip(): val.strip()}
|
277
|
+
return {}
|
278
|
+
elif target_type == int:
|
279
|
+
value = value.strip().lower()
|
280
|
+
if value.startswith('0x'):
|
281
|
+
return int(value, 16)
|
282
|
+
elif value.startswith('0o'):
|
283
|
+
return int(value, 8)
|
284
|
+
elif value.startswith('0b'):
|
285
|
+
return int(value, 2)
|
286
|
+
return int(value)
|
287
|
+
elif target_type == float:
|
288
|
+
return float(value)
|
289
|
+
elif target_type == complex:
|
290
|
+
return complex(value)
|
291
|
+
elif target_type == bytes:
|
292
|
+
return value.encode('utf-8')
|
293
|
+
elif target_type == bytearray:
|
294
|
+
return bytearray(value.encode('utf-8'))
|
295
|
+
elif target_type == set:
|
296
|
+
return set(value.split(','))
|
297
|
+
elif target_type == frozenset:
|
298
|
+
return frozenset(value.split(','))
|
299
|
+
elif target_type == range:
|
300
|
+
parts = value.split(':')
|
301
|
+
if len(parts) == 2:
|
302
|
+
return range(int(parts[0]), int(parts[1]))
|
303
|
+
elif len(parts) == 3:
|
304
|
+
return range(int(parts[0]), int(parts[1]), int(parts[2]))
|
305
|
+
raise ValueError("Invalid range format")
|
306
|
+
return target_type(value)
|
307
|
+
except (ValueError, TypeError) as e:
|
308
|
+
raise ConfigValueError(
|
309
|
+
f"无法将值 '{value}' 转换为类型 {target_type.__name__}",
|
310
|
+
file_path=None,
|
311
|
+
key=None
|
312
|
+
)
|
313
|
+
|
314
|
+
def get_value(self, file_path: Optional[Union[str, Path]] = None, key: str = None,
|
315
|
+
section: Optional[str] = None, default: Any = None,
|
316
|
+
value_type: Optional[Type[T]] = None) -> T:
|
317
|
+
"""获取指定配置项的值"""
|
318
|
+
if file_path is None:
|
319
|
+
self._ensure_file_open()
|
320
|
+
file_path = self._current_file
|
321
|
+
if not self._validate_key(key):
|
322
|
+
raise ConfigValueError(f"无效的键名: {key}", file_path=file_path, key=key)
|
323
|
+
|
324
|
+
config = self.read(file_path)
|
325
|
+
section = section or self.options.default_section
|
326
|
+
normalized_section = self._normalize_section(section)
|
327
|
+
|
328
|
+
original_section = self._get_original_section(str(file_path), normalized_section)
|
329
|
+
if original_section is None:
|
330
|
+
if default is not None:
|
331
|
+
return default
|
332
|
+
raise ConfigSectionNotFoundError(file_path, section)
|
333
|
+
|
334
|
+
if key not in config[original_section]:
|
335
|
+
if default is not None:
|
336
|
+
return default
|
337
|
+
raise ConfigKeyNotFoundError(file_path, original_section, key)
|
338
|
+
|
339
|
+
value = config[original_section][key]
|
340
|
+
|
341
|
+
if value_type is not None:
|
342
|
+
return self._convert_value(value, value_type)
|
343
|
+
|
344
|
+
return value
|
345
|
+
|
346
|
+
def get_values(self, keys: List[Tuple[str, str]],
|
347
|
+
file_path: Optional[Union[str, Path]] = None,
|
348
|
+
defaults: Optional[Dict[str, Any]] = None,
|
349
|
+
value_types: Optional[Dict[str, Type]] = None) -> Dict[str, Any]:
|
350
|
+
"""批量获取多个配置项的值"""
|
351
|
+
if file_path is None:
|
352
|
+
self._ensure_file_open()
|
353
|
+
file_path = self._current_file
|
354
|
+
defaults = defaults or {}
|
355
|
+
value_types = value_types or {}
|
356
|
+
result = {}
|
357
|
+
|
358
|
+
for section, key in keys:
|
359
|
+
try:
|
360
|
+
value = self.get_value(
|
361
|
+
file_path=file_path,
|
362
|
+
key=key,
|
363
|
+
section=section,
|
364
|
+
default=defaults.get(key),
|
365
|
+
value_type=value_types.get(key)
|
366
|
+
)
|
367
|
+
result[key] = value
|
368
|
+
except (ConfigSectionNotFoundError, ConfigKeyNotFoundError) as e:
|
369
|
+
if key in defaults:
|
370
|
+
result[key] = defaults[key]
|
371
|
+
else:
|
372
|
+
raise e
|
373
|
+
|
374
|
+
return result
|
375
|
+
|
376
|
+
def get_section_values(self, keys: List[str],
|
377
|
+
section: Optional[str] = None,
|
378
|
+
file_path: Optional[Union[str, Path]] = None,
|
379
|
+
defaults: Optional[Dict[str, Any]] = None,
|
380
|
+
value_types: Optional[Dict[str, Type]] = None) -> Tuple[Any, ...]:
|
381
|
+
"""获取指定节点下多个键的值元组"""
|
382
|
+
if file_path is None:
|
383
|
+
self._ensure_file_open()
|
384
|
+
file_path = self._current_file
|
385
|
+
defaults = defaults or {}
|
386
|
+
value_types = value_types or {}
|
387
|
+
result = []
|
388
|
+
|
389
|
+
for key in keys:
|
390
|
+
try:
|
391
|
+
value = self.get_value(
|
392
|
+
file_path=file_path,
|
393
|
+
key=key,
|
394
|
+
section=section,
|
395
|
+
default=defaults.get(key),
|
396
|
+
value_type=value_types.get(key)
|
397
|
+
)
|
398
|
+
result.append(value)
|
399
|
+
except (ConfigSectionNotFoundError, ConfigKeyNotFoundError) as e:
|
400
|
+
if key in defaults:
|
401
|
+
result.append(defaults[key])
|
402
|
+
else:
|
403
|
+
raise e
|
404
|
+
|
405
|
+
return tuple(result)
|
406
|
+
|
407
|
+
def set_value(self, key: str, value: Any,
|
408
|
+
section: Optional[str] = None,
|
409
|
+
file_path: Optional[Union[str, Path]] = None,
|
410
|
+
value_type: Optional[Type] = None) -> None:
|
411
|
+
"""设置指定配置项的值"""
|
412
|
+
if file_path is None:
|
413
|
+
self._ensure_file_open()
|
414
|
+
file_path = self._current_file
|
415
|
+
if not self._validate_key(key):
|
416
|
+
raise ConfigValueError(f"无效的键名: {key}", file_path=file_path, key=key)
|
417
|
+
|
418
|
+
original_lines = []
|
419
|
+
if file_path.exists():
|
420
|
+
with open(file_path, 'r', encoding=self.options.encoding) as file:
|
421
|
+
original_lines = file.readlines()
|
422
|
+
|
423
|
+
config = self.read(file_path)
|
424
|
+
|
425
|
+
if section not in config:
|
426
|
+
config[section] = {}
|
427
|
+
|
428
|
+
if value_type is not None:
|
429
|
+
try:
|
430
|
+
if value_type == bool:
|
431
|
+
if isinstance(value, str):
|
432
|
+
value = value.lower() in ('true', 'yes', '1', 'on')
|
433
|
+
else:
|
434
|
+
value = bool(value)
|
435
|
+
else:
|
436
|
+
value = value_type(value)
|
437
|
+
except (ValueError, TypeError) as e:
|
438
|
+
raise ConfigValueError(
|
439
|
+
f"无法将值 '{value}' 转换为类型 {value_type.__name__}",
|
440
|
+
file_path=file_path,
|
441
|
+
section=section,
|
442
|
+
key=key
|
443
|
+
)
|
444
|
+
|
445
|
+
if isinstance(value, bool):
|
446
|
+
value = str(value).lower()
|
447
|
+
else:
|
448
|
+
value = str(value)
|
449
|
+
|
450
|
+
config[section][key] = value
|
451
|
+
|
452
|
+
try:
|
453
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
454
|
+
|
455
|
+
with open(file_path, 'w', encoding=self.options.encoding) as file:
|
456
|
+
current_section = self.options.default_section
|
457
|
+
section_separators = {}
|
458
|
+
|
459
|
+
for line in original_lines:
|
460
|
+
stripped_line = line.strip()
|
461
|
+
|
462
|
+
if not stripped_line:
|
463
|
+
file.write(line)
|
464
|
+
continue
|
465
|
+
|
466
|
+
if stripped_line.startswith('[') and stripped_line.endswith(']'):
|
467
|
+
current_section = stripped_line[1:-1]
|
468
|
+
file.write(line)
|
469
|
+
continue
|
470
|
+
|
471
|
+
if self._is_comment_line(stripped_line):
|
472
|
+
file.write(line)
|
473
|
+
continue
|
474
|
+
|
475
|
+
key_value = self._split_key_value(stripped_line)
|
476
|
+
if key_value:
|
477
|
+
orig_key, orig_value = key_value
|
478
|
+
for sep in self.options.separators:
|
479
|
+
if sep in line:
|
480
|
+
section_separators.setdefault(current_section, {})[orig_key] = sep
|
481
|
+
break
|
482
|
+
|
483
|
+
if current_section == section and orig_key == key:
|
484
|
+
separator = section_separators.get(current_section, {}).get(orig_key, self.options.separators[0])
|
485
|
+
comment = ''
|
486
|
+
for style in self.options.comment_styles:
|
487
|
+
comment_match = re.search(fr'\s+{re.escape(style.value)}.*$', line)
|
488
|
+
if comment_match:
|
489
|
+
comment = comment_match.group(0)
|
490
|
+
break
|
491
|
+
file.write(f'{key}{separator}{value}{comment}\n')
|
492
|
+
else:
|
493
|
+
file.write(line)
|
494
|
+
else:
|
495
|
+
file.write(line)
|
496
|
+
|
497
|
+
if section not in [line.strip()[1:-1] for line in original_lines if line.strip().startswith('[') and line.strip().endswith(']')]:
|
498
|
+
file.write(f'\n[{section}]\n')
|
499
|
+
file.write(f'{key}={value}\n')
|
500
|
+
|
501
|
+
self._clear_cache(str(file_path))
|
502
|
+
|
503
|
+
except Exception as e:
|
504
|
+
raise ConfigWriteError(file_path, e)
|
505
|
+
|
506
|
+
def read(self, file_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]:
|
507
|
+
"""读取配置文件内容"""
|
508
|
+
if file_path is None:
|
509
|
+
self._ensure_file_open()
|
510
|
+
file_path = self._current_file
|
511
|
+
else:
|
512
|
+
file_path = Path(file_path)
|
513
|
+
|
514
|
+
cached_config = self._get_cached_config(str(file_path))
|
515
|
+
if cached_config is not None:
|
516
|
+
return cached_config
|
517
|
+
|
518
|
+
if not file_path.exists():
|
519
|
+
if not self.options.auto_create:
|
520
|
+
raise ConfigFileNotFoundError(file_path)
|
521
|
+
logger.info(f'配置文件不存在,将创建: {file_path}')
|
522
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
523
|
+
file_path.touch()
|
524
|
+
return {}
|
525
|
+
|
526
|
+
try:
|
527
|
+
with open(file_path, 'r', encoding=self.options.encoding) as file:
|
528
|
+
config = {}
|
529
|
+
current_section = self.options.default_section
|
530
|
+
section_comments = []
|
531
|
+
|
532
|
+
for line in file:
|
533
|
+
stripped_line = line.strip()
|
534
|
+
|
535
|
+
if not stripped_line or self._is_comment_line(stripped_line):
|
536
|
+
if self.options.preserve_comments:
|
537
|
+
section_comments.append(line.rstrip())
|
538
|
+
continue
|
539
|
+
|
540
|
+
if stripped_line.startswith('[') and stripped_line.endswith(']'):
|
541
|
+
current_section = stripped_line[1:-1]
|
542
|
+
if not self._validate_key(current_section):
|
543
|
+
raise ConfigValueError(
|
544
|
+
f"无效的节名: {current_section}",
|
545
|
+
file_path=file_path,
|
546
|
+
section=current_section
|
547
|
+
)
|
548
|
+
self._update_section_map(str(file_path), current_section)
|
549
|
+
if current_section not in config:
|
550
|
+
config[current_section] = {}
|
551
|
+
if self.options.preserve_comments:
|
552
|
+
self._comments_cache.setdefault(str(file_path), {}).setdefault(current_section, []).extend(section_comments)
|
553
|
+
section_comments = []
|
554
|
+
continue
|
555
|
+
|
556
|
+
key_value = self._split_key_value(stripped_line)
|
557
|
+
if key_value:
|
558
|
+
key, value = key_value
|
559
|
+
if not self._validate_key(key):
|
560
|
+
raise ConfigValueError(
|
561
|
+
f"无效的键名: {key}",
|
562
|
+
file_path=file_path,
|
563
|
+
section=current_section,
|
564
|
+
key=key
|
565
|
+
)
|
566
|
+
value, comment = self._extract_comment(value)
|
567
|
+
|
568
|
+
if self.options.strip_values:
|
569
|
+
value = value.strip()
|
570
|
+
|
571
|
+
if current_section not in config:
|
572
|
+
config[current_section] = {}
|
573
|
+
|
574
|
+
config[current_section][key] = value
|
575
|
+
if self.options.preserve_comments and comment:
|
576
|
+
self._comments_cache.setdefault(str(file_path), {}).setdefault(current_section, []).append(comment)
|
577
|
+
|
578
|
+
self._update_cache(str(file_path), config)
|
579
|
+
return config
|
580
|
+
|
581
|
+
except Exception as e:
|
582
|
+
raise ConfigReadError(file_path, e)
|
583
|
+
|
584
|
+
|
585
|
+
def main() -> None:
|
586
|
+
"""示例用法"""
|
587
|
+
config_file = Path('/Users/xigua/spd.txt')
|
588
|
+
|
589
|
+
# 方式1:使用上下文管理器
|
590
|
+
with ConfigParser() as parser:
|
591
|
+
parser.open(config_file)
|
592
|
+
host, port, username, password = parser.get_section_values(
|
593
|
+
keys=['host', 'port', 'username', 'password'],
|
594
|
+
section='mysql'
|
595
|
+
)
|
596
|
+
print("方式1结果:", host, port, username, password)
|
597
|
+
|
598
|
+
parser.set_value('username', 'root', section='mysql')
|
599
|
+
parser.set_value('port', 3306, section='mysql')
|
600
|
+
|
601
|
+
# 方式2:链式调用
|
602
|
+
parser = ConfigParser()
|
603
|
+
host, port, username, password = parser.open(config_file).get_section_values(
|
604
|
+
keys=['host', 'port', 'username', 'password'],
|
605
|
+
section='mysql'
|
606
|
+
)
|
607
|
+
print("\n方式2结果:", host, port, username, password)
|
608
|
+
|
609
|
+
# 方式3:传统方式
|
610
|
+
parser = ConfigParser()
|
611
|
+
host, port, username, password = parser.get_section_values(
|
612
|
+
file_path=config_file,
|
613
|
+
section='mysql',
|
614
|
+
keys=['host', 'port', 'username', 'password']
|
615
|
+
)
|
616
|
+
print("\n方式3结果:", host, port, username, password)
|
617
|
+
|
618
|
+
|
619
|
+
if __name__ == '__main__':
|
620
|
+
main()
|
@@ -1,11 +1,12 @@
|
|
1
1
|
mdbq/__init__.py,sha256=Il5Q9ATdX8yXqVxtP_nYqUhExzxPC_qk_WXQ_4h0exg,16
|
2
|
-
mdbq/__version__.py,sha256=
|
2
|
+
mdbq/__version__.py,sha256=gSoWvHL6N2Idp7W1joFJ-FzlUGBvhO24bsaGJ6I1x-Y,18
|
3
3
|
mdbq/aggregation/__init__.py,sha256=EeDqX2Aml6SPx8363J-v1lz0EcZtgwIBYyCJV6CcEDU,40
|
4
4
|
mdbq/aggregation/query_data.py,sha256=hdaB0vPh5BcTu9kLViRvM7OAE0b07D4jzAIipqxGI-I,166757
|
5
5
|
mdbq/log/__init__.py,sha256=Mpbrav0s0ifLL7lVDAuePEi1hJKiSHhxcv1byBKDl5E,15
|
6
6
|
mdbq/log/mylogger.py,sha256=9w_o5mYB3FooIxobq_lSa6oCYTKIhPxDFox-jeLtUHI,21714
|
7
7
|
mdbq/myconf/__init__.py,sha256=jso1oHcy6cJEfa7udS_9uO5X6kZLoPBF8l3wCYmr5dM,18
|
8
8
|
mdbq/myconf/myconf.py,sha256=39tLUBVlWQZzQfrwk7YoLEfipo11fpwWjaLBHcUt2qM,33341
|
9
|
+
mdbq/myconf/myconf2.py,sha256=kaHhOvKMVOilu9JYKfsefF08tUyC99B8aWUZJvc_oh8,25481
|
9
10
|
mdbq/mysql/__init__.py,sha256=A_DPJyAoEvTSFojiI2e94zP0FKtCkkwKP1kYUCSyQzo,11
|
10
11
|
mdbq/mysql/deduplicator.py,sha256=kAnkI_vnN8CchgDQAFzeh0M0vLXE2oWq9SfDPNZZ3v0,73215
|
11
12
|
mdbq/mysql/mysql.py,sha256=pDg771xBugCMSTWeskIFTi3pFLgaqgyG3smzf-86Wn8,56772
|
@@ -24,7 +25,7 @@ mdbq/redis/__init__.py,sha256=YtgBlVSMDphtpwYX248wGge1x-Ex_mMufz4-8W0XRmA,12
|
|
24
25
|
mdbq/redis/getredis.py,sha256=vpBuNc22uj9Vr-_Dh25_wpwWM1e-072EAAIBdB_IpL0,23494
|
25
26
|
mdbq/spider/__init__.py,sha256=RBMFXGy_jd1HXZhngB2T2XTvJqki8P_Fr-pBcwijnew,18
|
26
27
|
mdbq/spider/aikucun.py,sha256=juOqpr_dHeE1RyjCu67VcpzoJAWMO7FKv0i8KiH8WUo,21552
|
27
|
-
mdbq-4.0.
|
28
|
-
mdbq-4.0.
|
29
|
-
mdbq-4.0.
|
30
|
-
mdbq-4.0.
|
28
|
+
mdbq-4.0.22.dist-info/METADATA,sha256=EVHw5Bw16kqgOfKjnTmRY9SpDDpj882dD0UjB_ogT6w,364
|
29
|
+
mdbq-4.0.22.dist-info/WHEEL,sha256=jB7zZ3N9hIM9adW7qlTAyycLYW9npaWKLRzaoVcLKcM,91
|
30
|
+
mdbq-4.0.22.dist-info/top_level.txt,sha256=2FQ-uLnCSB-OwFiWntzmwosW3X2Xqsg0ewh1axsaylA,5
|
31
|
+
mdbq-4.0.22.dist-info/RECORD,,
|
File without changes
|
File without changes
|