dc-cmnutils 0.0.3__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.
- dc_cmnutils-0.0.3/LICENSE.TXT +19 -0
- dc_cmnutils-0.0.3/PKG-INFO +34 -0
- dc_cmnutils-0.0.3/README.md +21 -0
- dc_cmnutils-0.0.3/pyproject.toml +33 -0
- dc_cmnutils-0.0.3/setup.cfg +4 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/basicdata/convert.py +192 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/basicdata/convert_basic.py +393 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/basicdata/data.py +588 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/basicdata/json.py +94 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/basicdata/object.py +814 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/collection/collection.py +757 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/database/database_access.py +213 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/database/database_accessor.py +287 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/database/db_operater.py +283 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/database/dbutil.py +389 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/io/file/cfg/config.py +262 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/io/file/file.py +212 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/io/file/file_utils.py +605 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/io/log/log.py +43 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/io/log/log_utils.py +50 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/net/email.py +185 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/net/http.py +468 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/net/net.py +252 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/sys/env/linuxenv.py +384 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/sys/env/windowsenv.py +235 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/sys/envutil.py +442 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/sys/processutil.py +447 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/sys/sys.py +640 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/sys/sys_utils.py +580 -0
- dc_cmnutils-0.0.3/src/dc/cmnutils/sys/threadutil.py +315 -0
- dc_cmnutils-0.0.3/src/dc_cmnutils.egg-info/PKG-INFO +34 -0
- dc_cmnutils-0.0.3/src/dc_cmnutils.egg-info/SOURCES.txt +33 -0
- dc_cmnutils-0.0.3/src/dc_cmnutils.egg-info/dependency_links.txt +1 -0
- dc_cmnutils-0.0.3/src/dc_cmnutils.egg-info/requires.txt +4 -0
- dc_cmnutils-0.0.3/src/dc_cmnutils.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2026 The Python Packaging Authority
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dc-cmnutils
|
|
3
|
+
Version: 0.0.3
|
|
4
|
+
Summary: A common utility library for dc.
|
|
5
|
+
Author-email: dc <627815355@qq.com>
|
|
6
|
+
Requires-Python: >=3.8
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE.TXT
|
|
9
|
+
Requires-Dist: dc-cmnlib>=0.0.1
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# dc-cmnutils
|
|
15
|
+
|
|
16
|
+
[](https://pypi.org/project/dc-cmnutils/)
|
|
17
|
+
[](https://pypi.org/project/dc-cmnutils/)
|
|
18
|
+
[](https://opensource.org/licenses/MIT)
|
|
19
|
+
|
|
20
|
+
A lightweight and reliable Python utility library. It provides commonly used helper functions for object handling, string manipulation, and more, helping you reduce boilerplate code in daily development.
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- **Ready to Use**: Offers a rich collection of static utility methods without requiring instantiation.
|
|
25
|
+
- **Safe & Robust**: Built-in null safety handling to prevent common runtime exceptions.
|
|
26
|
+
- **Zero Dependencies**: Core functionalities rely on no third-party libraries, keeping your project lightweight.
|
|
27
|
+
- **IDE Friendly**: Fully supports code completion and static type checking in modern IDEs.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
Install via pip:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install dc-cmnutils
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# dc-cmnutils
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/dc-cmnutils/)
|
|
4
|
+
[](https://pypi.org/project/dc-cmnutils/)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
|
|
7
|
+
A lightweight and reliable Python utility library. It provides commonly used helper functions for object handling, string manipulation, and more, helping you reduce boilerplate code in daily development.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- **Ready to Use**: Offers a rich collection of static utility methods without requiring instantiation.
|
|
12
|
+
- **Safe & Robust**: Built-in null safety handling to prevent common runtime exceptions.
|
|
13
|
+
- **Zero Dependencies**: Core functionalities rely on no third-party libraries, keeping your project lightweight.
|
|
14
|
+
- **IDE Friendly**: Fully supports code completion and static type checking in modern IDEs.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
Install via pip:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install dc-cmnutils
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
# 定义构建后端及所需的依赖
|
|
3
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
4
|
+
build-backend = "setuptools.build_meta"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
# 基础元数据
|
|
8
|
+
name = "dc-cmnutils"
|
|
9
|
+
version = "0.0.3"
|
|
10
|
+
description = "A common utility library for dc."
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
requires-python = ">=3.8"
|
|
13
|
+
|
|
14
|
+
# 作者信息(可根据实际情况修改)
|
|
15
|
+
authors = [
|
|
16
|
+
{ name = "dc", email = "627815355@qq.com" }
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
# 依赖项(目前为空,后续按需添加)
|
|
20
|
+
dependencies = [
|
|
21
|
+
# "dc-cmnlib"
|
|
22
|
+
"dc-cmnlib>=0.0.1",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
# 可选的依赖项(例如测试工具)
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = [
|
|
28
|
+
"pytest>=7.0"
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
# 针对 src 布局的包发现配置
|
|
32
|
+
[tool.setuptools.packages.find]
|
|
33
|
+
where = ["src"]
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
from typing import TypeVar, Any, Union, List, Optional
|
|
2
|
+
import json
|
|
3
|
+
from datetime import datetime, date
|
|
4
|
+
from dc.cmnlib.basicdata.convert import ConvertHelper
|
|
5
|
+
|
|
6
|
+
from dc.cmnutils.basicdata.convert_basic import ConvertUtilsBasic
|
|
7
|
+
|
|
8
|
+
T = TypeVar('T')
|
|
9
|
+
U = TypeVar('U')
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ConvertUtils(ConvertUtilsBasic):
|
|
13
|
+
"""数据类型转换工具类"""
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
def to_str(value: Any, default: str = '') -> str:
|
|
17
|
+
"""转换为字符串"""
|
|
18
|
+
try:
|
|
19
|
+
if value is None:
|
|
20
|
+
return default
|
|
21
|
+
return str(value)
|
|
22
|
+
except (ValueError, TypeError):
|
|
23
|
+
return default
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def to_int(value: Any, default: int = 0) -> int:
|
|
27
|
+
"""转换为整数"""
|
|
28
|
+
try:
|
|
29
|
+
if value is None:
|
|
30
|
+
return default
|
|
31
|
+
return int(value)
|
|
32
|
+
except (ValueError, TypeError):
|
|
33
|
+
return default
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def to_float(value: Any, default: float = 0.0) -> float:
|
|
37
|
+
"""转换为浮点数"""
|
|
38
|
+
try:
|
|
39
|
+
if value is None:
|
|
40
|
+
return default
|
|
41
|
+
return float(value)
|
|
42
|
+
except (ValueError, TypeError):
|
|
43
|
+
return default
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def to_bool(value: Any, default: bool = False) -> bool:
|
|
47
|
+
"""转换为布尔值"""
|
|
48
|
+
if value is None:
|
|
49
|
+
return default
|
|
50
|
+
|
|
51
|
+
if isinstance(value, bool):
|
|
52
|
+
return value
|
|
53
|
+
|
|
54
|
+
if isinstance(value, str):
|
|
55
|
+
lower_val = value.lower()
|
|
56
|
+
if lower_val in ('true', 'yes', '1', 'on'):
|
|
57
|
+
return True
|
|
58
|
+
elif lower_val in ('false', 'no', '0', 'off'):
|
|
59
|
+
return False
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
return bool(value)
|
|
63
|
+
except (ValueError, TypeError):
|
|
64
|
+
return default
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def to_list(value: Any, default: Optional[List] = None) -> List:
|
|
68
|
+
"""转换为列表"""
|
|
69
|
+
if default is None:
|
|
70
|
+
default = []
|
|
71
|
+
|
|
72
|
+
if value is None:
|
|
73
|
+
return default
|
|
74
|
+
|
|
75
|
+
if isinstance(value, list):
|
|
76
|
+
return value
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
# 尝试将可迭代对象转换为列表
|
|
80
|
+
return list(value)
|
|
81
|
+
except (TypeError, ValueError):
|
|
82
|
+
# 如果无法转换,则返回包含原始值的列表
|
|
83
|
+
return [value]
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def to_dict(value: Any, default: Optional[dict] = None) -> dict:
|
|
87
|
+
"""转换为字典"""
|
|
88
|
+
if default is None:
|
|
89
|
+
default = {}
|
|
90
|
+
|
|
91
|
+
if value is None:
|
|
92
|
+
return default
|
|
93
|
+
|
|
94
|
+
if isinstance(value, dict):
|
|
95
|
+
return value
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
# 尝试将对象转换为字典
|
|
99
|
+
return dict(value)
|
|
100
|
+
except (TypeError, ValueError):
|
|
101
|
+
return default
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def to_datetime(value: Any, fmt: str = '%Y-%m-%d %H:%M:%S', default: Optional[datetime] = None) -> Optional[
|
|
105
|
+
datetime]:
|
|
106
|
+
"""转换为datetime对象"""
|
|
107
|
+
if value is None:
|
|
108
|
+
return default
|
|
109
|
+
|
|
110
|
+
if isinstance(value, datetime):
|
|
111
|
+
return value
|
|
112
|
+
|
|
113
|
+
if isinstance(value, date):
|
|
114
|
+
return datetime(value.year, value.month, value.day)
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
if isinstance(value, (int, float)):
|
|
118
|
+
# 假设是时间戳
|
|
119
|
+
return datetime.fromtimestamp(value)
|
|
120
|
+
elif isinstance(value, str):
|
|
121
|
+
# 尝试解析字符串
|
|
122
|
+
return datetime.strptime(value, fmt)
|
|
123
|
+
except (ValueError, TypeError, OSError):
|
|
124
|
+
pass
|
|
125
|
+
|
|
126
|
+
return default
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def to_date(value: Any, fmt: str = '%Y-%m-%d', default: Optional[date] = None) -> Optional[date]:
|
|
130
|
+
"""转换为date对象"""
|
|
131
|
+
if value is None:
|
|
132
|
+
return default
|
|
133
|
+
|
|
134
|
+
if isinstance(value, date):
|
|
135
|
+
return value if isinstance(value, date) else value.date()
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
if isinstance(value, (int, float)):
|
|
139
|
+
# 假设是时间戳
|
|
140
|
+
dt = datetime.fromtimestamp(value)
|
|
141
|
+
return dt.date()
|
|
142
|
+
elif isinstance(value, str):
|
|
143
|
+
# 尝试解析字符串
|
|
144
|
+
dt = datetime.strptime(value, fmt)
|
|
145
|
+
return dt.date()
|
|
146
|
+
elif isinstance(value, datetime):
|
|
147
|
+
return value.date()
|
|
148
|
+
except (ValueError, TypeError, OSError):
|
|
149
|
+
pass
|
|
150
|
+
|
|
151
|
+
return default
|
|
152
|
+
|
|
153
|
+
@staticmethod
|
|
154
|
+
def to_type(value: Any, target_type: T, default: Optional[T] = None) -> Optional[T]:
|
|
155
|
+
"""泛型转换方法,尝试将值转换为指定类型"""
|
|
156
|
+
if value is None:
|
|
157
|
+
return default
|
|
158
|
+
|
|
159
|
+
if isinstance(value, type(target_type)):
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
# 尝试使用目标类型的构造函数进行转换
|
|
164
|
+
return target_type(value)
|
|
165
|
+
except (ValueError, TypeError):
|
|
166
|
+
return default
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
def to_json(value: Any, default: Optional[str] = None) -> Optional[str]:
|
|
170
|
+
"""转换为JSON字符串"""
|
|
171
|
+
if value is None:
|
|
172
|
+
return default
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
return json.dumps(value)
|
|
176
|
+
except (TypeError, ValueError):
|
|
177
|
+
return default
|
|
178
|
+
|
|
179
|
+
@staticmethod
|
|
180
|
+
def from_json(value: Any, default: Optional[Any] = None) -> Optional[Any]:
|
|
181
|
+
"""从JSON字符串解析为Python对象"""
|
|
182
|
+
if value is None:
|
|
183
|
+
return default
|
|
184
|
+
|
|
185
|
+
if not isinstance(value, str):
|
|
186
|
+
return default
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
return json.loads(value)
|
|
190
|
+
except (json.JSONDecodeError, TypeError):
|
|
191
|
+
return default
|
|
192
|
+
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""数据转换帮助类
|
|
2
|
+
|
|
3
|
+
提供各种数据类型之间的转换功能,支持安全转换,避免异常。
|
|
4
|
+
所有方法均为静态方法,线程安全,适用于多线程环境。
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import xml.etree.ElementTree as ET
|
|
8
|
+
from typing import Any, List, Dict, Optional, Union
|
|
9
|
+
|
|
10
|
+
from dc.cmnlib.basicdata.convert import ConvertHelper
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConvertUtilsBasic(ConvertHelper):
|
|
14
|
+
"""数据转换帮助类"""
|
|
15
|
+
|
|
16
|
+
@staticmethod
|
|
17
|
+
def to_str(value: Any, default: str = "") -> str:
|
|
18
|
+
"""安全转换为字符串
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
value: 任意类型的值
|
|
22
|
+
default: 默认值,转换失败时返回
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
str: 转换后的字符串
|
|
26
|
+
"""
|
|
27
|
+
if value is None:
|
|
28
|
+
return default
|
|
29
|
+
try:
|
|
30
|
+
return str(value)
|
|
31
|
+
except (TypeError, ValueError):
|
|
32
|
+
return default
|
|
33
|
+
|
|
34
|
+
@staticmethod
|
|
35
|
+
def to_int(value: Any, default: int = 0) -> int:
|
|
36
|
+
"""安全转换为整数
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
value: 任意类型的值
|
|
40
|
+
default: 默认值,转换失败时返回
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
int: 转换后的整数
|
|
44
|
+
"""
|
|
45
|
+
if value is None:
|
|
46
|
+
return default
|
|
47
|
+
try:
|
|
48
|
+
if isinstance(value, float):
|
|
49
|
+
return int(value)
|
|
50
|
+
return int(value)
|
|
51
|
+
except (TypeError, ValueError):
|
|
52
|
+
return default
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def to_float(value: Any, default: float = 0.0) -> float:
|
|
56
|
+
"""安全转换为浮点数
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
value: 任意类型的值
|
|
60
|
+
default: 默认值,转换失败时返回
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
float: 转换后的浮点数
|
|
64
|
+
"""
|
|
65
|
+
if value is None:
|
|
66
|
+
return default
|
|
67
|
+
try:
|
|
68
|
+
return float(value)
|
|
69
|
+
except (TypeError, ValueError):
|
|
70
|
+
return default
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def to_bool(value: Any, default: bool = False) -> bool:
|
|
74
|
+
"""安全转换为布尔值
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
value: 任意类型的值
|
|
78
|
+
default: 默认值,转换失败时返回
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
bool: 转换后的布尔值
|
|
82
|
+
"""
|
|
83
|
+
if value is None:
|
|
84
|
+
return default
|
|
85
|
+
try:
|
|
86
|
+
if isinstance(value, bool):
|
|
87
|
+
return value
|
|
88
|
+
if isinstance(value, str):
|
|
89
|
+
lower = value.lower().strip()
|
|
90
|
+
return lower in ('true', 'yes', '1', 'on')
|
|
91
|
+
if isinstance(value, (int, float)):
|
|
92
|
+
return value != 0
|
|
93
|
+
return bool(value)
|
|
94
|
+
except (TypeError, ValueError):
|
|
95
|
+
return default
|
|
96
|
+
|
|
97
|
+
@staticmethod
|
|
98
|
+
def to_list(value: Any, default: List[Any] = None) -> List[Any]:
|
|
99
|
+
"""安全转换为列表
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
value: 任意类型的值
|
|
103
|
+
default: 默认值,转换失败时返回
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
List[Any]: 转换后的列表
|
|
107
|
+
"""
|
|
108
|
+
if default is None:
|
|
109
|
+
default = []
|
|
110
|
+
if value is None:
|
|
111
|
+
return default
|
|
112
|
+
try:
|
|
113
|
+
if isinstance(value, list):
|
|
114
|
+
return value
|
|
115
|
+
if isinstance(value, (tuple, set)):
|
|
116
|
+
return list(value)
|
|
117
|
+
if isinstance(value, str):
|
|
118
|
+
return [value]
|
|
119
|
+
return [value]
|
|
120
|
+
except (TypeError, ValueError):
|
|
121
|
+
return default
|
|
122
|
+
|
|
123
|
+
@staticmethod
|
|
124
|
+
def to_dict(value: Any, default: Dict[str, Any] = None) -> Dict[str, Any]:
|
|
125
|
+
"""安全转换为字典
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
value: 任意类型的值
|
|
129
|
+
default: 默认值,转换失败时返回
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
Dict[str, Any]: 转换后的字典
|
|
133
|
+
"""
|
|
134
|
+
if default is None:
|
|
135
|
+
default = {}
|
|
136
|
+
if value is None:
|
|
137
|
+
return default
|
|
138
|
+
try:
|
|
139
|
+
if isinstance(value, dict):
|
|
140
|
+
return value
|
|
141
|
+
return default
|
|
142
|
+
except (TypeError, ValueError):
|
|
143
|
+
return default
|
|
144
|
+
|
|
145
|
+
@staticmethod
|
|
146
|
+
def json_to_dict(json_str: str, default: Dict[str, Any] = None) -> Dict[str, Any]:
|
|
147
|
+
"""将 JSON 字符串转换为字典
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
json_str: JSON 字符串
|
|
151
|
+
default: 默认值,转换失败时返回
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
Dict[str, Any]: 转换后的字典
|
|
155
|
+
"""
|
|
156
|
+
if default is None:
|
|
157
|
+
default = {}
|
|
158
|
+
if not json_str or not isinstance(json_str, str):
|
|
159
|
+
return default
|
|
160
|
+
try:
|
|
161
|
+
return json.loads(json_str)
|
|
162
|
+
except (json.JSONDecodeError, TypeError, ValueError):
|
|
163
|
+
return default
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def dict_to_json(dictionary: Dict[str, Any], indent: int = 2) -> str:
|
|
167
|
+
"""将字典转换为 JSON 字符串
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
dictionary: 字典对象
|
|
171
|
+
indent: 缩进空格数,默认为 2
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
str: JSON 字符串
|
|
175
|
+
"""
|
|
176
|
+
if not dictionary or not isinstance(dictionary, dict):
|
|
177
|
+
return "{}"
|
|
178
|
+
try:
|
|
179
|
+
return json.dumps(dictionary, indent=indent, ensure_ascii=False)
|
|
180
|
+
except (TypeError, ValueError):
|
|
181
|
+
return "{}"
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def json_to_list(json_str: str, default: List[Any] = None) -> List[Any]:
|
|
185
|
+
"""将 JSON 字符串转换为列表
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
json_str: JSON 字符串
|
|
189
|
+
default: 默认值,转换失败时返回
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
List[Any]: 转换后的列表
|
|
193
|
+
"""
|
|
194
|
+
if default is None:
|
|
195
|
+
default = []
|
|
196
|
+
if not json_str or not isinstance(json_str, str):
|
|
197
|
+
return default
|
|
198
|
+
try:
|
|
199
|
+
result = json.loads(json_str)
|
|
200
|
+
if isinstance(result, list):
|
|
201
|
+
return result
|
|
202
|
+
return [result]
|
|
203
|
+
except (json.JSONDecodeError, TypeError, ValueError):
|
|
204
|
+
return default
|
|
205
|
+
|
|
206
|
+
@staticmethod
|
|
207
|
+
def list_to_json(lst: List[Any], indent: int = 2) -> str:
|
|
208
|
+
"""将列表转换为 JSON 字符串
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
lst: 列表对象
|
|
212
|
+
indent: 缩进空格数,默认为 2
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
str: JSON 字符串
|
|
216
|
+
"""
|
|
217
|
+
if not lst or not isinstance(lst, list):
|
|
218
|
+
return "[]"
|
|
219
|
+
try:
|
|
220
|
+
return json.dumps(lst, indent=indent, ensure_ascii=False)
|
|
221
|
+
except (TypeError, ValueError):
|
|
222
|
+
return "[]"
|
|
223
|
+
|
|
224
|
+
@staticmethod
|
|
225
|
+
def xml_to_dict(xml_str: str, default: Dict[str, Any] = None) -> Dict[str, Any]:
|
|
226
|
+
"""将 XML 字符串转换为字典
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
xml_str: XML 字符串
|
|
230
|
+
default: 默认值,转换失败时返回
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
Dict[str, Any]: 转换后的字典
|
|
234
|
+
"""
|
|
235
|
+
if default is None:
|
|
236
|
+
default = {}
|
|
237
|
+
if not xml_str or not isinstance(xml_str, str):
|
|
238
|
+
return default
|
|
239
|
+
try:
|
|
240
|
+
root = ET.fromstring(xml_str)
|
|
241
|
+
return ConvertUtilsBasic._xml_element_to_dict(root)
|
|
242
|
+
except (ET.ParseError, TypeError, ValueError):
|
|
243
|
+
return default
|
|
244
|
+
|
|
245
|
+
@staticmethod
|
|
246
|
+
def _xml_element_to_dict(element: ET.Element) -> Dict[str, Any]:
|
|
247
|
+
"""将 XML 元素转换为字典(内部方法)
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
element: XML 元素
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
Dict[str, Any]: 转换后的字典
|
|
254
|
+
"""
|
|
255
|
+
result = {}
|
|
256
|
+
if element.text and element.text.strip():
|
|
257
|
+
if len(element) == 0:
|
|
258
|
+
return element.text.strip()
|
|
259
|
+
|
|
260
|
+
for child in element:
|
|
261
|
+
child_dict = ConvertUtilsBasic._xml_element_to_dict(child)
|
|
262
|
+
if child.tag in result:
|
|
263
|
+
if not isinstance(result[child.tag], list):
|
|
264
|
+
result[child.tag] = [result[child.tag]]
|
|
265
|
+
result[child.tag].append(child_dict)
|
|
266
|
+
else:
|
|
267
|
+
result[child.tag] = child_dict
|
|
268
|
+
|
|
269
|
+
result.update(element.attrib)
|
|
270
|
+
return result
|
|
271
|
+
|
|
272
|
+
@staticmethod
|
|
273
|
+
def dict_to_xml(dictionary: Dict[str, Any], root_tag: str = 'root') -> str:
|
|
274
|
+
"""将字典转换为 XML 字符串
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
dictionary: 字典对象
|
|
278
|
+
root_tag: 根节点标签名,默认为 'root'
|
|
279
|
+
|
|
280
|
+
Returns:
|
|
281
|
+
str: XML 字符串
|
|
282
|
+
"""
|
|
283
|
+
if not dictionary or not isinstance(dictionary, dict):
|
|
284
|
+
return f"<{root_tag}/>"
|
|
285
|
+
try:
|
|
286
|
+
root = ET.Element(root_tag)
|
|
287
|
+
ConvertUtilsBasic._dict_to_xml_element(root, dictionary)
|
|
288
|
+
return ET.tostring(root, encoding='unicode', method='xml')
|
|
289
|
+
except (TypeError, ValueError):
|
|
290
|
+
return f"<{root_tag}/>"
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def _dict_to_xml_element(parent: ET.Element, dictionary: Dict[str, Any]) -> None:
|
|
294
|
+
"""将字典转换为 XML 元素(内部方法)
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
parent: 父元素
|
|
298
|
+
dictionary: 字典对象
|
|
299
|
+
"""
|
|
300
|
+
for key, value in dictionary.items():
|
|
301
|
+
if isinstance(value, dict):
|
|
302
|
+
child = ET.SubElement(parent, key)
|
|
303
|
+
ConvertUtilsBasic._dict_to_xml_element(child, value)
|
|
304
|
+
elif isinstance(value, list):
|
|
305
|
+
for item in value:
|
|
306
|
+
child = ET.SubElement(parent, key)
|
|
307
|
+
if isinstance(item, dict):
|
|
308
|
+
ConvertUtilsBasic._dict_to_xml_element(child, item)
|
|
309
|
+
else:
|
|
310
|
+
child.text = str(item)
|
|
311
|
+
else:
|
|
312
|
+
child = ET.SubElement(parent, key)
|
|
313
|
+
child.text = str(value)
|
|
314
|
+
|
|
315
|
+
@staticmethod
|
|
316
|
+
def to_bytes(value: Any, encoding: str = 'utf-8', errors: str = 'replace') -> bytes:
|
|
317
|
+
"""安全转换为字节数组
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
value: 任意类型的值
|
|
321
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
322
|
+
errors: 错误处理方式,默认为 'replace'
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
bytes: 转换后的字节数组
|
|
326
|
+
"""
|
|
327
|
+
if value is None:
|
|
328
|
+
return b""
|
|
329
|
+
try:
|
|
330
|
+
if isinstance(value, bytes):
|
|
331
|
+
return value
|
|
332
|
+
if isinstance(value, str):
|
|
333
|
+
return value.encode(encoding, errors=errors)
|
|
334
|
+
return str(value).encode(encoding, errors=errors)
|
|
335
|
+
except (TypeError, ValueError):
|
|
336
|
+
return b""
|
|
337
|
+
|
|
338
|
+
@staticmethod
|
|
339
|
+
def bytes_to_str(value: bytes, encoding: str = 'utf-8', errors: str = 'replace') -> str:
|
|
340
|
+
"""将字节数组转换为字符串
|
|
341
|
+
|
|
342
|
+
Args:
|
|
343
|
+
value: 字节数组
|
|
344
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
345
|
+
errors: 错误处理方式,默认为 'replace'
|
|
346
|
+
|
|
347
|
+
Returns:
|
|
348
|
+
str: 转换后的字符串
|
|
349
|
+
"""
|
|
350
|
+
if value is None:
|
|
351
|
+
return ""
|
|
352
|
+
try:
|
|
353
|
+
if isinstance(value, str):
|
|
354
|
+
return value
|
|
355
|
+
return value.decode(encoding, errors=errors)
|
|
356
|
+
except (TypeError, ValueError):
|
|
357
|
+
return ""
|
|
358
|
+
|
|
359
|
+
@staticmethod
|
|
360
|
+
def str_to_hex(s: str, encoding: str = 'utf-8') -> str:
|
|
361
|
+
"""将字符串转换为十六进制
|
|
362
|
+
|
|
363
|
+
Args:
|
|
364
|
+
s: 字符串
|
|
365
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
366
|
+
|
|
367
|
+
Returns:
|
|
368
|
+
str: 十六进制字符串
|
|
369
|
+
"""
|
|
370
|
+
if not s or not isinstance(s, str):
|
|
371
|
+
return ""
|
|
372
|
+
try:
|
|
373
|
+
return s.encode(encoding).hex()
|
|
374
|
+
except (TypeError, ValueError):
|
|
375
|
+
return ""
|
|
376
|
+
|
|
377
|
+
@staticmethod
|
|
378
|
+
def hex_to_str(hex_str: str, encoding: str = 'utf-8') -> str:
|
|
379
|
+
"""将十六进制字符串转换为普通字符串
|
|
380
|
+
|
|
381
|
+
Args:
|
|
382
|
+
hex_str: 十六进制字符串
|
|
383
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
384
|
+
|
|
385
|
+
Returns:
|
|
386
|
+
str: 转换后的字符串
|
|
387
|
+
"""
|
|
388
|
+
if not hex_str or not isinstance(hex_str, str):
|
|
389
|
+
return ""
|
|
390
|
+
try:
|
|
391
|
+
return bytes.fromhex(hex_str).decode(encoding)
|
|
392
|
+
except (TypeError, ValueError):
|
|
393
|
+
return ""
|