dc-cmnutils 1.0.0__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.
Potentially problematic release.
This version of dc-cmnutils might be problematic. Click here for more details.
- dc/__init__.py +0 -0
- dc/cmnutils/__init__.py +0 -0
- dc/cmnutils/basicdata/__init__.py +0 -0
- dc/cmnutils/basicdata/basic.py +0 -0
- dc/cmnutils/basicdata/basicdata.py +586 -0
- dc/cmnutils/basicdata/convert.py +189 -0
- dc/cmnutils/basicdata/convert_basic.py +391 -0
- dc/cmnutils/basicdata/json.py +94 -0
- dc/cmnutils/basicdata/object.py +814 -0
- dc/cmnutils/collection/__init__.py +0 -0
- dc/cmnutils/collection/collection.py +757 -0
- dc/cmnutils/database/__init__.py +0 -0
- dc/cmnutils/database/database_access.py +213 -0
- dc/cmnutils/database/database_accessor.py +287 -0
- dc/cmnutils/database/db_operater.py +283 -0
- dc/cmnutils/database/dbutil.py +389 -0
- dc/cmnutils/definitions/__init__.py +0 -0
- dc/cmnutils/definitions/definitions.py +91 -0
- dc/cmnutils/definitions/result.py +201 -0
- dc/cmnutils/io/__init__.py +0 -0
- dc/cmnutils/io/file/__init__.py +0 -0
- dc/cmnutils/io/file/cfg/__init__.py +0 -0
- dc/cmnutils/io/file/cfg/config.py +262 -0
- dc/cmnutils/io/file/file.py +214 -0
- dc/cmnutils/io/file/file_utils.py +605 -0
- dc/cmnutils/io/log/__init__.py +0 -0
- dc/cmnutils/io/log/log.py +43 -0
- dc/cmnutils/io/log/log_utils.py +50 -0
- dc/cmnutils/misc/__init__.py +0 -0
- dc/cmnutils/net/__init__.py +0 -0
- dc/cmnutils/net/email.py +185 -0
- dc/cmnutils/net/net.py +251 -0
- dc/cmnutils/net/net_utils.py +468 -0
- dc/cmnutils/sys/__init__.py +0 -0
- dc/cmnutils/sys/env/__init__.py +0 -0
- dc/cmnutils/sys/env/linuxenv.py +384 -0
- dc/cmnutils/sys/env/windowsenv.py +235 -0
- dc/cmnutils/sys/envutil.py +442 -0
- dc/cmnutils/sys/processutil.py +447 -0
- dc/cmnutils/sys/sys.py +640 -0
- dc/cmnutils/sys/sys_utils.py +580 -0
- dc/cmnutils/sys/threadutil.py +315 -0
- dc_cmnutils-1.0.0.dist-info/METADATA +36 -0
- dc_cmnutils-1.0.0.dist-info/RECORD +47 -0
- dc_cmnutils-1.0.0.dist-info/WHEEL +5 -0
- dc_cmnutils-1.0.0.dist-info/licenses/LICENSE.TXT +19 -0
- dc_cmnutils-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
from typing import TypeVar, Any, Union, List, Optional
|
|
2
|
+
import json
|
|
3
|
+
from datetime import datetime, date
|
|
4
|
+
|
|
5
|
+
T = TypeVar('T')
|
|
6
|
+
U = TypeVar('U')
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ConverUtil:
|
|
10
|
+
"""数据类型转换工具类"""
|
|
11
|
+
|
|
12
|
+
@staticmethod
|
|
13
|
+
def to_str(value: Any, default: str = '') -> str:
|
|
14
|
+
"""转换为字符串"""
|
|
15
|
+
try:
|
|
16
|
+
if value is None:
|
|
17
|
+
return default
|
|
18
|
+
return str(value)
|
|
19
|
+
except (ValueError, TypeError):
|
|
20
|
+
return default
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def to_int(value: Any, default: int = 0) -> int:
|
|
24
|
+
"""转换为整数"""
|
|
25
|
+
try:
|
|
26
|
+
if value is None:
|
|
27
|
+
return default
|
|
28
|
+
return int(value)
|
|
29
|
+
except (ValueError, TypeError):
|
|
30
|
+
return default
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def to_float(value: Any, default: float = 0.0) -> float:
|
|
34
|
+
"""转换为浮点数"""
|
|
35
|
+
try:
|
|
36
|
+
if value is None:
|
|
37
|
+
return default
|
|
38
|
+
return float(value)
|
|
39
|
+
except (ValueError, TypeError):
|
|
40
|
+
return default
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def to_bool(value: Any, default: bool = False) -> bool:
|
|
44
|
+
"""转换为布尔值"""
|
|
45
|
+
if value is None:
|
|
46
|
+
return default
|
|
47
|
+
|
|
48
|
+
if isinstance(value, bool):
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
if isinstance(value, str):
|
|
52
|
+
lower_val = value.lower()
|
|
53
|
+
if lower_val in ('true', 'yes', '1', 'on'):
|
|
54
|
+
return True
|
|
55
|
+
elif lower_val in ('false', 'no', '0', 'off'):
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
return bool(value)
|
|
60
|
+
except (ValueError, TypeError):
|
|
61
|
+
return default
|
|
62
|
+
|
|
63
|
+
@staticmethod
|
|
64
|
+
def to_list(value: Any, default: Optional[List] = None) -> List:
|
|
65
|
+
"""转换为列表"""
|
|
66
|
+
if default is None:
|
|
67
|
+
default = []
|
|
68
|
+
|
|
69
|
+
if value is None:
|
|
70
|
+
return default
|
|
71
|
+
|
|
72
|
+
if isinstance(value, list):
|
|
73
|
+
return value
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
# 尝试将可迭代对象转换为列表
|
|
77
|
+
return list(value)
|
|
78
|
+
except (TypeError, ValueError):
|
|
79
|
+
# 如果无法转换,则返回包含原始值的列表
|
|
80
|
+
return [value]
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def to_dict(value: Any, default: Optional[dict] = None) -> dict:
|
|
84
|
+
"""转换为字典"""
|
|
85
|
+
if default is None:
|
|
86
|
+
default = {}
|
|
87
|
+
|
|
88
|
+
if value is None:
|
|
89
|
+
return default
|
|
90
|
+
|
|
91
|
+
if isinstance(value, dict):
|
|
92
|
+
return value
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
# 尝试将对象转换为字典
|
|
96
|
+
return dict(value)
|
|
97
|
+
except (TypeError, ValueError):
|
|
98
|
+
return default
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def to_datetime(value: Any, fmt: str = '%Y-%m-%d %H:%M:%S', default: Optional[datetime] = None) -> Optional[
|
|
102
|
+
datetime]:
|
|
103
|
+
"""转换为datetime对象"""
|
|
104
|
+
if value is None:
|
|
105
|
+
return default
|
|
106
|
+
|
|
107
|
+
if isinstance(value, datetime):
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
if isinstance(value, date):
|
|
111
|
+
return datetime(value.year, value.month, value.day)
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
if isinstance(value, (int, float)):
|
|
115
|
+
# 假设是时间戳
|
|
116
|
+
return datetime.fromtimestamp(value)
|
|
117
|
+
elif isinstance(value, str):
|
|
118
|
+
# 尝试解析字符串
|
|
119
|
+
return datetime.strptime(value, fmt)
|
|
120
|
+
except (ValueError, TypeError, OSError):
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
return default
|
|
124
|
+
|
|
125
|
+
@staticmethod
|
|
126
|
+
def to_date(value: Any, fmt: str = '%Y-%m-%d', default: Optional[date] = None) -> Optional[date]:
|
|
127
|
+
"""转换为date对象"""
|
|
128
|
+
if value is None:
|
|
129
|
+
return default
|
|
130
|
+
|
|
131
|
+
if isinstance(value, date):
|
|
132
|
+
return value if isinstance(value, date) else value.date()
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
if isinstance(value, (int, float)):
|
|
136
|
+
# 假设是时间戳
|
|
137
|
+
dt = datetime.fromtimestamp(value)
|
|
138
|
+
return dt.date()
|
|
139
|
+
elif isinstance(value, str):
|
|
140
|
+
# 尝试解析字符串
|
|
141
|
+
dt = datetime.strptime(value, fmt)
|
|
142
|
+
return dt.date()
|
|
143
|
+
elif isinstance(value, datetime):
|
|
144
|
+
return value.date()
|
|
145
|
+
except (ValueError, TypeError, OSError):
|
|
146
|
+
pass
|
|
147
|
+
|
|
148
|
+
return default
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def to_type(value: Any, target_type: T, default: Optional[T] = None) -> Optional[T]:
|
|
152
|
+
"""泛型转换方法,尝试将值转换为指定类型"""
|
|
153
|
+
if value is None:
|
|
154
|
+
return default
|
|
155
|
+
|
|
156
|
+
if isinstance(value, type(target_type)):
|
|
157
|
+
return value
|
|
158
|
+
|
|
159
|
+
try:
|
|
160
|
+
# 尝试使用目标类型的构造函数进行转换
|
|
161
|
+
return target_type(value)
|
|
162
|
+
except (ValueError, TypeError):
|
|
163
|
+
return default
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def to_json(value: Any, default: Optional[str] = None) -> Optional[str]:
|
|
167
|
+
"""转换为JSON字符串"""
|
|
168
|
+
if value is None:
|
|
169
|
+
return default
|
|
170
|
+
|
|
171
|
+
try:
|
|
172
|
+
return json.dumps(value)
|
|
173
|
+
except (TypeError, ValueError):
|
|
174
|
+
return default
|
|
175
|
+
|
|
176
|
+
@staticmethod
|
|
177
|
+
def from_json(value: Any, default: Optional[Any] = None) -> Optional[Any]:
|
|
178
|
+
"""从JSON字符串解析为Python对象"""
|
|
179
|
+
if value is None:
|
|
180
|
+
return default
|
|
181
|
+
|
|
182
|
+
if not isinstance(value, str):
|
|
183
|
+
return default
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
return json.loads(value)
|
|
187
|
+
except (json.JSONDecodeError, TypeError):
|
|
188
|
+
return default
|
|
189
|
+
|
|
@@ -0,0 +1,391 @@
|
|
|
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
|
+
|
|
11
|
+
class ConvertUtils:
|
|
12
|
+
"""数据转换帮助类"""
|
|
13
|
+
|
|
14
|
+
@staticmethod
|
|
15
|
+
def to_str(value: Any, default: str = "") -> str:
|
|
16
|
+
"""安全转换为字符串
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
value: 任意类型的值
|
|
20
|
+
default: 默认值,转换失败时返回
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
str: 转换后的字符串
|
|
24
|
+
"""
|
|
25
|
+
if value is None:
|
|
26
|
+
return default
|
|
27
|
+
try:
|
|
28
|
+
return str(value)
|
|
29
|
+
except (TypeError, ValueError):
|
|
30
|
+
return default
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def to_int(value: Any, default: int = 0) -> int:
|
|
34
|
+
"""安全转换为整数
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
value: 任意类型的值
|
|
38
|
+
default: 默认值,转换失败时返回
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
int: 转换后的整数
|
|
42
|
+
"""
|
|
43
|
+
if value is None:
|
|
44
|
+
return default
|
|
45
|
+
try:
|
|
46
|
+
if isinstance(value, float):
|
|
47
|
+
return int(value)
|
|
48
|
+
return int(value)
|
|
49
|
+
except (TypeError, ValueError):
|
|
50
|
+
return default
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def to_float(value: Any, default: float = 0.0) -> float:
|
|
54
|
+
"""安全转换为浮点数
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
value: 任意类型的值
|
|
58
|
+
default: 默认值,转换失败时返回
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
float: 转换后的浮点数
|
|
62
|
+
"""
|
|
63
|
+
if value is None:
|
|
64
|
+
return default
|
|
65
|
+
try:
|
|
66
|
+
return float(value)
|
|
67
|
+
except (TypeError, ValueError):
|
|
68
|
+
return default
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def to_bool(value: Any, default: bool = False) -> bool:
|
|
72
|
+
"""安全转换为布尔值
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
value: 任意类型的值
|
|
76
|
+
default: 默认值,转换失败时返回
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
bool: 转换后的布尔值
|
|
80
|
+
"""
|
|
81
|
+
if value is None:
|
|
82
|
+
return default
|
|
83
|
+
try:
|
|
84
|
+
if isinstance(value, bool):
|
|
85
|
+
return value
|
|
86
|
+
if isinstance(value, str):
|
|
87
|
+
lower = value.lower().strip()
|
|
88
|
+
return lower in ('true', 'yes', '1', 'on')
|
|
89
|
+
if isinstance(value, (int, float)):
|
|
90
|
+
return value != 0
|
|
91
|
+
return bool(value)
|
|
92
|
+
except (TypeError, ValueError):
|
|
93
|
+
return default
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def to_list(value: Any, default: List[Any] = None) -> List[Any]:
|
|
97
|
+
"""安全转换为列表
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
value: 任意类型的值
|
|
101
|
+
default: 默认值,转换失败时返回
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
List[Any]: 转换后的列表
|
|
105
|
+
"""
|
|
106
|
+
if default is None:
|
|
107
|
+
default = []
|
|
108
|
+
if value is None:
|
|
109
|
+
return default
|
|
110
|
+
try:
|
|
111
|
+
if isinstance(value, list):
|
|
112
|
+
return value
|
|
113
|
+
if isinstance(value, (tuple, set)):
|
|
114
|
+
return list(value)
|
|
115
|
+
if isinstance(value, str):
|
|
116
|
+
return [value]
|
|
117
|
+
return [value]
|
|
118
|
+
except (TypeError, ValueError):
|
|
119
|
+
return default
|
|
120
|
+
|
|
121
|
+
@staticmethod
|
|
122
|
+
def to_dict(value: Any, default: Dict[str, Any] = None) -> Dict[str, Any]:
|
|
123
|
+
"""安全转换为字典
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
value: 任意类型的值
|
|
127
|
+
default: 默认值,转换失败时返回
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
Dict[str, Any]: 转换后的字典
|
|
131
|
+
"""
|
|
132
|
+
if default is None:
|
|
133
|
+
default = {}
|
|
134
|
+
if value is None:
|
|
135
|
+
return default
|
|
136
|
+
try:
|
|
137
|
+
if isinstance(value, dict):
|
|
138
|
+
return value
|
|
139
|
+
return default
|
|
140
|
+
except (TypeError, ValueError):
|
|
141
|
+
return default
|
|
142
|
+
|
|
143
|
+
@staticmethod
|
|
144
|
+
def json_to_dict(json_str: str, default: Dict[str, Any] = None) -> Dict[str, Any]:
|
|
145
|
+
"""将 JSON 字符串转换为字典
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
json_str: JSON 字符串
|
|
149
|
+
default: 默认值,转换失败时返回
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
Dict[str, Any]: 转换后的字典
|
|
153
|
+
"""
|
|
154
|
+
if default is None:
|
|
155
|
+
default = {}
|
|
156
|
+
if not json_str or not isinstance(json_str, str):
|
|
157
|
+
return default
|
|
158
|
+
try:
|
|
159
|
+
return json.loads(json_str)
|
|
160
|
+
except (json.JSONDecodeError, TypeError, ValueError):
|
|
161
|
+
return default
|
|
162
|
+
|
|
163
|
+
@staticmethod
|
|
164
|
+
def dict_to_json(dictionary: Dict[str, Any], indent: int = 2) -> str:
|
|
165
|
+
"""将字典转换为 JSON 字符串
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
dictionary: 字典对象
|
|
169
|
+
indent: 缩进空格数,默认为 2
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
str: JSON 字符串
|
|
173
|
+
"""
|
|
174
|
+
if not dictionary or not isinstance(dictionary, dict):
|
|
175
|
+
return "{}"
|
|
176
|
+
try:
|
|
177
|
+
return json.dumps(dictionary, indent=indent, ensure_ascii=False)
|
|
178
|
+
except (TypeError, ValueError):
|
|
179
|
+
return "{}"
|
|
180
|
+
|
|
181
|
+
@staticmethod
|
|
182
|
+
def json_to_list(json_str: str, default: List[Any] = None) -> List[Any]:
|
|
183
|
+
"""将 JSON 字符串转换为列表
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
json_str: JSON 字符串
|
|
187
|
+
default: 默认值,转换失败时返回
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
List[Any]: 转换后的列表
|
|
191
|
+
"""
|
|
192
|
+
if default is None:
|
|
193
|
+
default = []
|
|
194
|
+
if not json_str or not isinstance(json_str, str):
|
|
195
|
+
return default
|
|
196
|
+
try:
|
|
197
|
+
result = json.loads(json_str)
|
|
198
|
+
if isinstance(result, list):
|
|
199
|
+
return result
|
|
200
|
+
return [result]
|
|
201
|
+
except (json.JSONDecodeError, TypeError, ValueError):
|
|
202
|
+
return default
|
|
203
|
+
|
|
204
|
+
@staticmethod
|
|
205
|
+
def list_to_json(lst: List[Any], indent: int = 2) -> str:
|
|
206
|
+
"""将列表转换为 JSON 字符串
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
lst: 列表对象
|
|
210
|
+
indent: 缩进空格数,默认为 2
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
str: JSON 字符串
|
|
214
|
+
"""
|
|
215
|
+
if not lst or not isinstance(lst, list):
|
|
216
|
+
return "[]"
|
|
217
|
+
try:
|
|
218
|
+
return json.dumps(lst, indent=indent, ensure_ascii=False)
|
|
219
|
+
except (TypeError, ValueError):
|
|
220
|
+
return "[]"
|
|
221
|
+
|
|
222
|
+
@staticmethod
|
|
223
|
+
def xml_to_dict(xml_str: str, default: Dict[str, Any] = None) -> Dict[str, Any]:
|
|
224
|
+
"""将 XML 字符串转换为字典
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
xml_str: XML 字符串
|
|
228
|
+
default: 默认值,转换失败时返回
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
Dict[str, Any]: 转换后的字典
|
|
232
|
+
"""
|
|
233
|
+
if default is None:
|
|
234
|
+
default = {}
|
|
235
|
+
if not xml_str or not isinstance(xml_str, str):
|
|
236
|
+
return default
|
|
237
|
+
try:
|
|
238
|
+
root = ET.fromstring(xml_str)
|
|
239
|
+
return ConvertUtils._xml_element_to_dict(root)
|
|
240
|
+
except (ET.ParseError, TypeError, ValueError):
|
|
241
|
+
return default
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def _xml_element_to_dict(element: ET.Element) -> Dict[str, Any]:
|
|
245
|
+
"""将 XML 元素转换为字典(内部方法)
|
|
246
|
+
|
|
247
|
+
Args:
|
|
248
|
+
element: XML 元素
|
|
249
|
+
|
|
250
|
+
Returns:
|
|
251
|
+
Dict[str, Any]: 转换后的字典
|
|
252
|
+
"""
|
|
253
|
+
result = {}
|
|
254
|
+
if element.text and element.text.strip():
|
|
255
|
+
if len(element) == 0:
|
|
256
|
+
return element.text.strip()
|
|
257
|
+
|
|
258
|
+
for child in element:
|
|
259
|
+
child_dict = ConvertUtils._xml_element_to_dict(child)
|
|
260
|
+
if child.tag in result:
|
|
261
|
+
if not isinstance(result[child.tag], list):
|
|
262
|
+
result[child.tag] = [result[child.tag]]
|
|
263
|
+
result[child.tag].append(child_dict)
|
|
264
|
+
else:
|
|
265
|
+
result[child.tag] = child_dict
|
|
266
|
+
|
|
267
|
+
result.update(element.attrib)
|
|
268
|
+
return result
|
|
269
|
+
|
|
270
|
+
@staticmethod
|
|
271
|
+
def dict_to_xml(dictionary: Dict[str, Any], root_tag: str = 'root') -> str:
|
|
272
|
+
"""将字典转换为 XML 字符串
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
dictionary: 字典对象
|
|
276
|
+
root_tag: 根节点标签名,默认为 'root'
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
str: XML 字符串
|
|
280
|
+
"""
|
|
281
|
+
if not dictionary or not isinstance(dictionary, dict):
|
|
282
|
+
return f"<{root_tag}/>"
|
|
283
|
+
try:
|
|
284
|
+
root = ET.Element(root_tag)
|
|
285
|
+
ConvertUtils._dict_to_xml_element(root, dictionary)
|
|
286
|
+
return ET.tostring(root, encoding='unicode', method='xml')
|
|
287
|
+
except (TypeError, ValueError):
|
|
288
|
+
return f"<{root_tag}/>"
|
|
289
|
+
|
|
290
|
+
@staticmethod
|
|
291
|
+
def _dict_to_xml_element(parent: ET.Element, dictionary: Dict[str, Any]) -> None:
|
|
292
|
+
"""将字典转换为 XML 元素(内部方法)
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
parent: 父元素
|
|
296
|
+
dictionary: 字典对象
|
|
297
|
+
"""
|
|
298
|
+
for key, value in dictionary.items():
|
|
299
|
+
if isinstance(value, dict):
|
|
300
|
+
child = ET.SubElement(parent, key)
|
|
301
|
+
ConvertUtils._dict_to_xml_element(child, value)
|
|
302
|
+
elif isinstance(value, list):
|
|
303
|
+
for item in value:
|
|
304
|
+
child = ET.SubElement(parent, key)
|
|
305
|
+
if isinstance(item, dict):
|
|
306
|
+
ConvertUtils._dict_to_xml_element(child, item)
|
|
307
|
+
else:
|
|
308
|
+
child.text = str(item)
|
|
309
|
+
else:
|
|
310
|
+
child = ET.SubElement(parent, key)
|
|
311
|
+
child.text = str(value)
|
|
312
|
+
|
|
313
|
+
@staticmethod
|
|
314
|
+
def to_bytes(value: Any, encoding: str = 'utf-8', errors: str = 'replace') -> bytes:
|
|
315
|
+
"""安全转换为字节数组
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
value: 任意类型的值
|
|
319
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
320
|
+
errors: 错误处理方式,默认为 'replace'
|
|
321
|
+
|
|
322
|
+
Returns:
|
|
323
|
+
bytes: 转换后的字节数组
|
|
324
|
+
"""
|
|
325
|
+
if value is None:
|
|
326
|
+
return b""
|
|
327
|
+
try:
|
|
328
|
+
if isinstance(value, bytes):
|
|
329
|
+
return value
|
|
330
|
+
if isinstance(value, str):
|
|
331
|
+
return value.encode(encoding, errors=errors)
|
|
332
|
+
return str(value).encode(encoding, errors=errors)
|
|
333
|
+
except (TypeError, ValueError):
|
|
334
|
+
return b""
|
|
335
|
+
|
|
336
|
+
@staticmethod
|
|
337
|
+
def bytes_to_str(value: bytes, encoding: str = 'utf-8', errors: str = 'replace') -> str:
|
|
338
|
+
"""将字节数组转换为字符串
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
value: 字节数组
|
|
342
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
343
|
+
errors: 错误处理方式,默认为 'replace'
|
|
344
|
+
|
|
345
|
+
Returns:
|
|
346
|
+
str: 转换后的字符串
|
|
347
|
+
"""
|
|
348
|
+
if value is None:
|
|
349
|
+
return ""
|
|
350
|
+
try:
|
|
351
|
+
if isinstance(value, str):
|
|
352
|
+
return value
|
|
353
|
+
return value.decode(encoding, errors=errors)
|
|
354
|
+
except (TypeError, ValueError):
|
|
355
|
+
return ""
|
|
356
|
+
|
|
357
|
+
@staticmethod
|
|
358
|
+
def str_to_hex(s: str, encoding: str = 'utf-8') -> str:
|
|
359
|
+
"""将字符串转换为十六进制
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
s: 字符串
|
|
363
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
364
|
+
|
|
365
|
+
Returns:
|
|
366
|
+
str: 十六进制字符串
|
|
367
|
+
"""
|
|
368
|
+
if not s or not isinstance(s, str):
|
|
369
|
+
return ""
|
|
370
|
+
try:
|
|
371
|
+
return s.encode(encoding).hex()
|
|
372
|
+
except (TypeError, ValueError):
|
|
373
|
+
return ""
|
|
374
|
+
|
|
375
|
+
@staticmethod
|
|
376
|
+
def hex_to_str(hex_str: str, encoding: str = 'utf-8') -> str:
|
|
377
|
+
"""将十六进制字符串转换为普通字符串
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
hex_str: 十六进制字符串
|
|
381
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
382
|
+
|
|
383
|
+
Returns:
|
|
384
|
+
str: 转换后的字符串
|
|
385
|
+
"""
|
|
386
|
+
if not hex_str or not isinstance(hex_str, str):
|
|
387
|
+
return ""
|
|
388
|
+
try:
|
|
389
|
+
return bytes.fromhex(hex_str).decode(encoding)
|
|
390
|
+
except (TypeError, ValueError):
|
|
391
|
+
return ""
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import enum
|
|
3
|
+
import dataclasses
|
|
4
|
+
from typing import TypeVar, Type, Any, Union, get_type_hints
|
|
5
|
+
from datetime import datetime, date
|
|
6
|
+
|
|
7
|
+
# 定义泛型类型变量
|
|
8
|
+
T = TypeVar('T')
|
|
9
|
+
|
|
10
|
+
class JsonUtils:
|
|
11
|
+
"""
|
|
12
|
+
JSON 序列化与反序列化工具类,支持泛型及多种数据类型。
|
|
13
|
+
仅依赖 Python 标准库。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
@staticmethod
|
|
17
|
+
def serialize(obj: Any, **kwargs) -> str:
|
|
18
|
+
"""
|
|
19
|
+
将 Python 对象序列化为 JSON 字符串。
|
|
20
|
+
支持 dataclass, Enum, datetime, date 等类型。
|
|
21
|
+
"""
|
|
22
|
+
def default_serializer(o):
|
|
23
|
+
if isinstance(o, (datetime, date)):
|
|
24
|
+
return o.isoformat()
|
|
25
|
+
if dataclasses.is_dataclass(o) and not isinstance(o, type):
|
|
26
|
+
return dataclasses.asdict(o)
|
|
27
|
+
if isinstance(o, enum.Enum):
|
|
28
|
+
return o.value
|
|
29
|
+
raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
|
|
30
|
+
|
|
31
|
+
return json.dumps(obj, default=default_serializer, **kwargs)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def deserialize(cls, json_str: str, target_type: Type[T]) -> T:
|
|
35
|
+
"""
|
|
36
|
+
将 JSON 字符串反序列化为指定类型的 Python 对象。
|
|
37
|
+
支持泛型,例如: JsonUtils.deserialize('{"name":"test"}', MyClass)
|
|
38
|
+
"""
|
|
39
|
+
data = json.loads(json_str)
|
|
40
|
+
return cls._convert(data, target_type)
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def _convert(cls, data: Any, target_type: Type[T]) -> T:
|
|
44
|
+
"""
|
|
45
|
+
内部递归转换方法,根据目标类型将字典/列表转换为对应对象。
|
|
46
|
+
"""
|
|
47
|
+
# 1. 处理 None 或基础类型
|
|
48
|
+
if data is None or target_type in (str, int, float, bool):
|
|
49
|
+
return data
|
|
50
|
+
|
|
51
|
+
# 2. 处理 Union 类型 (如 Optional[MyClass])
|
|
52
|
+
origin = getattr(target_type, '__origin__', None)
|
|
53
|
+
if origin is Union:
|
|
54
|
+
args = getattr(target_type, '__args__', ())
|
|
55
|
+
# 尝试按顺序匹配,跳过 NoneType
|
|
56
|
+
for arg in args:
|
|
57
|
+
if arg is type(None):
|
|
58
|
+
continue
|
|
59
|
+
try:
|
|
60
|
+
return cls._convert(data, arg)
|
|
61
|
+
except (ValueError, TypeError, KeyError):
|
|
62
|
+
continue
|
|
63
|
+
return data
|
|
64
|
+
|
|
65
|
+
# 3. 处理 List 泛型 (如 List[MyClass])
|
|
66
|
+
if origin is list:
|
|
67
|
+
item_type = getattr(target_type, '__args__', (Any,))[0]
|
|
68
|
+
return [cls._convert(item, item_type) for item in data]
|
|
69
|
+
|
|
70
|
+
# 4. 处理 Dict 泛型 (如 Dict[str, MyClass])
|
|
71
|
+
if origin is dict:
|
|
72
|
+
key_type, val_type = getattr(target_type, '__args__', (Any, Any))
|
|
73
|
+
return {
|
|
74
|
+
cls._convert(k, key_type): cls._convert(v, val_type)
|
|
75
|
+
for k, v in data.items()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
# 5. 处理 Enum
|
|
79
|
+
if isinstance(target_type, type) and issubclass(target_type, enum.Enum):
|
|
80
|
+
return target_type(data)
|
|
81
|
+
|
|
82
|
+
# 6. 处理 Dataclass
|
|
83
|
+
if dataclasses.is_dataclass(target_type) and isinstance(data, dict):
|
|
84
|
+
hints = get_type_hints(target_type)
|
|
85
|
+
init_kwargs = {}
|
|
86
|
+
for key, val in data.items():
|
|
87
|
+
if key in hints:
|
|
88
|
+
init_kwargs[key] = cls._convert(val, hints[key])
|
|
89
|
+
else:
|
|
90
|
+
init_kwargs[key] = val
|
|
91
|
+
return target_type(**init_kwargs)
|
|
92
|
+
|
|
93
|
+
# 7. 其他情况直接返回
|
|
94
|
+
return data
|