dc-cmnutils 0.0.3__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.
@@ -0,0 +1,588 @@
1
+ """基础数据操作帮助类
2
+
3
+ 提供字符串、数字、列表、字典等基础数据类型的常用操作封装。
4
+ 所有方法均为静态方法,线程安全,适用于多线程环境。
5
+ """
6
+ import re
7
+ import hashlib
8
+ import random
9
+ import string
10
+ from datetime import datetime
11
+ from typing import Any, List, Dict, Optional, Union
12
+
13
+ from dc.cmnlib.basicdata.data import DataHelper
14
+
15
+
16
+ class DataUtils(DataHelper):
17
+ """基础数据操作帮助类"""
18
+
19
+ @staticmethod
20
+ def is_empty(value: Any) -> bool:
21
+ """判断值是否为空
22
+
23
+ Args:
24
+ value: 任意类型的值
25
+
26
+ Returns:
27
+ bool: 如果值为空返回 True,否则返回 False
28
+ """
29
+ if value is None:
30
+ return True
31
+ if isinstance(value, str):
32
+ return value.strip() == ""
33
+ if isinstance(value, (list, tuple, dict, set)):
34
+ return len(value) == 0
35
+ return False
36
+
37
+ @staticmethod
38
+ def is_not_empty(value: Any) -> bool:
39
+ """判断值是否不为空
40
+
41
+ Args:
42
+ value: 任意类型的值
43
+
44
+ Returns:
45
+ bool: 如果值不为空返回 True,否则返回 False
46
+ """
47
+ return not DataUtils.is_empty(value)
48
+
49
+ @staticmethod
50
+ def safe_get(dictionary: Dict[str, Any], key: str, default: Any = None) -> Any:
51
+ """安全获取字典值,避免 KeyError
52
+
53
+ Args:
54
+ dictionary: 字典对象
55
+ key: 键名
56
+ default: 默认值,当键不存在时返回
57
+
58
+ Returns:
59
+ Any: 字典中对应键的值,或默认值
60
+ """
61
+ if dictionary is None or not isinstance(dictionary, dict):
62
+ return default
63
+ return dictionary.get(key, default)
64
+
65
+ @staticmethod
66
+ def safe_index(lst: List[Any], index: int, default: Any = None) -> Any:
67
+ """安全获取列表元素,避免 IndexError
68
+
69
+ Args:
70
+ lst: 列表对象
71
+ index: 索引位置
72
+ default: 默认值,当索引超出范围时返回
73
+
74
+ Returns:
75
+ Any: 列表中对应索引的元素,或默认值
76
+ """
77
+ if lst is None or not isinstance(lst, list):
78
+ return default
79
+ try:
80
+ return lst[index]
81
+ except IndexError:
82
+ return default
83
+
84
+ @staticmethod
85
+ def remove_duplicates(lst: List[Any]) -> List[Any]:
86
+ """移除列表中的重复元素,保持原有顺序
87
+
88
+ Args:
89
+ lst: 列表对象
90
+
91
+ Returns:
92
+ List[Any]: 去重后的列表
93
+ """
94
+ if lst is None:
95
+ return []
96
+ seen = set()
97
+ result = []
98
+ for item in lst:
99
+ if item not in seen:
100
+ seen.add(item)
101
+ result.append(item)
102
+ return result
103
+
104
+ @staticmethod
105
+ def merge_dicts(*dicts: Dict[str, Any]) -> Dict[str, Any]:
106
+ """合并多个字典,后面的字典会覆盖前面的相同键
107
+
108
+ Args:
109
+ *dicts: 多个字典对象
110
+
111
+ Returns:
112
+ Dict[str, Any]: 合并后的字典
113
+ """
114
+ result = {}
115
+ for d in dicts:
116
+ if isinstance(d, dict):
117
+ result.update(d)
118
+ return result
119
+
120
+ @staticmethod
121
+ def split_string(s: str, separator: str = ',', strip: bool = True) -> List[str]:
122
+ """分割字符串为列表
123
+
124
+ Args:
125
+ s: 要分割的字符串
126
+ separator: 分隔符,默认为逗号
127
+ strip: 是否去除每个元素的首尾空格,默认为 True
128
+
129
+ Returns:
130
+ List[str]: 分割后的字符串列表
131
+ """
132
+ if DataUtils.is_empty(s):
133
+ return []
134
+ parts = s.split(separator)
135
+ if strip:
136
+ return [p.strip() for p in parts if p.strip()]
137
+ return parts
138
+
139
+ @staticmethod
140
+ def join_strings(lst: List[str], separator: str = ',') -> str:
141
+ """将字符串列表连接为一个字符串
142
+
143
+ Args:
144
+ lst: 字符串列表
145
+ separator: 连接符,默认为逗号
146
+
147
+ Returns:
148
+ str: 连接后的字符串
149
+ """
150
+ if lst is None or not isinstance(lst, list):
151
+ return ""
152
+ return separator.join(str(item) for item in lst)
153
+
154
+ @staticmethod
155
+ def truncate_string(s: str, max_length: int, suffix: str = '...') -> str:
156
+ """截断字符串,超过最大长度时添加后缀
157
+
158
+ Args:
159
+ s: 原始字符串
160
+ max_length: 最大长度
161
+ suffix: 后缀,默认为 '...'
162
+
163
+ Returns:
164
+ str: 截断后的字符串
165
+ """
166
+ if DataUtils.is_empty(s):
167
+ return ""
168
+ if len(s) <= max_length:
169
+ return s
170
+ return s[:max_length - len(suffix)] + suffix
171
+
172
+ @staticmethod
173
+ def generate_random_string(length: int = 16, chars: str = None) -> str:
174
+ """生成随机字符串
175
+
176
+ Args:
177
+ length: 字符串长度,默认为 16
178
+ chars: 可选的字符集,默认为字母和数字
179
+
180
+ Returns:
181
+ str: 随机生成的字符串
182
+ """
183
+ if chars is None:
184
+ chars = string.ascii_letters + string.digits
185
+ return ''.join(random.choice(chars) for _ in range(length))
186
+
187
+ @staticmethod
188
+ def generate_random_number(min_value: int = 0, max_value: int = 100) -> int:
189
+ """生成随机整数
190
+
191
+ Args:
192
+ min_value: 最小值,默认为 0
193
+ max_value: 最大值,默认为 100
194
+
195
+ Returns:
196
+ int: 随机整数
197
+ """
198
+ return random.randint(min_value, max_value)
199
+
200
+ @staticmethod
201
+ def calculate_hash(data: Any, algorithm: str = 'md5') -> str:
202
+ """计算数据的哈希值
203
+
204
+ Args:
205
+ data: 要计算哈希的数据
206
+ algorithm: 哈希算法,支持 'md5', 'sha1', 'sha256', 'sha512'
207
+
208
+ Returns:
209
+ str: 十六进制哈希值
210
+ """
211
+ if data is None:
212
+ return ""
213
+
214
+ if isinstance(data, str):
215
+ data = data.encode('utf-8')
216
+ elif isinstance(data, (int, float)):
217
+ data = str(data).encode('utf-8')
218
+ elif not isinstance(data, bytes):
219
+ data = str(data).encode('utf-8')
220
+
221
+ hash_obj = hashlib.new(algorithm)
222
+ hash_obj.update(data)
223
+ return hash_obj.hexdigest()
224
+
225
+ @staticmethod
226
+ def format_datetime(dt: datetime = None, format_str: str = '%Y-%m-%d %H:%M:%S') -> str:
227
+ """格式化日期时间
228
+
229
+ Args:
230
+ dt: 日期时间对象,默认为当前时间
231
+ format_str: 格式化字符串,默认为 '%Y-%m-%d %H:%M:%S'
232
+
233
+ Returns:
234
+ str: 格式化后的日期时间字符串
235
+ """
236
+ if dt is None:
237
+ dt = datetime.now()
238
+ return dt.strftime(format_str)
239
+
240
+ @staticmethod
241
+ def is_valid_email(email: str) -> bool:
242
+ """验证邮箱格式是否有效
243
+
244
+ Args:
245
+ email: 邮箱地址
246
+
247
+ Returns:
248
+ bool: 如果格式有效返回 True,否则返回 False
249
+ """
250
+ if DataUtils.is_empty(email):
251
+ return False
252
+ pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
253
+ return re.match(pattern, email) is not None
254
+
255
+ @staticmethod
256
+ def is_valid_phone(phone: str) -> bool:
257
+ """验证手机号格式是否有效(中国手机号)
258
+
259
+ Args:
260
+ phone: 手机号码
261
+
262
+ Returns:
263
+ bool: 如果格式有效返回 True,否则返回 False
264
+ """
265
+ if DataUtils.is_empty(phone):
266
+ return False
267
+ pattern = r'^1[3-9]\d{9}$'
268
+ return re.match(pattern, phone) is not None
269
+
270
+ @staticmethod
271
+ def is_valid_url(url: str) -> bool:
272
+ """验证 URL 格式是否有效
273
+
274
+ Args:
275
+ url: 网址
276
+
277
+ Returns:
278
+ bool: 如果格式有效返回 True,否则返回 False
279
+ """
280
+ if DataUtils.is_empty(url):
281
+ return False
282
+ pattern = r'^https?://[\w\.-]+(?:/[\w\.-]*)*$'
283
+ return re.match(pattern, url) is not None
284
+
285
+ @staticmethod
286
+ def clamp(value: Union[int, float], min_value: Union[int, float], max_value: Union[int, float]) -> Union[int, float]:
287
+ """将值限制在指定范围内
288
+
289
+ Args:
290
+ value: 要限制的值
291
+ min_value: 最小值
292
+ max_value: 最大值
293
+
294
+ Returns:
295
+ Union[int, float]: 限制后的值
296
+ """
297
+ return max(min_value, min(value, max_value))
298
+
299
+ @staticmethod
300
+ def to_bool(value: Any) -> bool:
301
+ """将值转换为布尔值
302
+
303
+ Args:
304
+ value: 任意类型的值
305
+
306
+ Returns:
307
+ bool: 转换后的布尔值
308
+ """
309
+ if isinstance(value, bool):
310
+ return value
311
+ if isinstance(value, str):
312
+ lower = value.lower().strip()
313
+ return lower in ('true', 'yes', '1', 'on')
314
+ if isinstance(value, int):
315
+ return value != 0
316
+ if isinstance(value, float):
317
+ return value != 0.0
318
+ return bool(value)
319
+
320
+ @staticmethod
321
+ def trim(s: str) -> str:
322
+ """去除字符串首尾空格
323
+
324
+ Args:
325
+ s: 字符串
326
+
327
+ Returns:
328
+ str: 去除首尾空格后的字符串
329
+ """
330
+ if s is None:
331
+ return ""
332
+ return s.strip()
333
+
334
+ @staticmethod
335
+ def to_upper(s: str) -> str:
336
+ """转换为大写
337
+
338
+ Args:
339
+ s: 字符串
340
+
341
+ Returns:
342
+ str: 大写字符串
343
+ """
344
+ if s is None:
345
+ return ""
346
+ return s.upper()
347
+
348
+ @staticmethod
349
+ def to_lower(s: str) -> str:
350
+ """转换为小写
351
+
352
+ Args:
353
+ s: 字符串
354
+
355
+ Returns:
356
+ str: 小写字符串
357
+ """
358
+ if s is None:
359
+ return ""
360
+ return s.lower()
361
+
362
+ @staticmethod
363
+ def starts_with(s: str, prefix: str) -> bool:
364
+ """判断字符串是否以指定前缀开头
365
+
366
+ Args:
367
+ s: 字符串
368
+ prefix: 前缀
369
+
370
+ Returns:
371
+ bool: 是否以指定前缀开头
372
+ """
373
+ if s is None or prefix is None:
374
+ return False
375
+ return s.startswith(prefix)
376
+
377
+ @staticmethod
378
+ def ends_with(s: str, suffix: str) -> bool:
379
+ """判断字符串是否以指定后缀结尾
380
+
381
+ Args:
382
+ s: 字符串
383
+ suffix: 后缀
384
+
385
+ Returns:
386
+ bool: 是否以指定后缀结尾
387
+ """
388
+ if s is None or suffix is None:
389
+ return False
390
+ return s.endswith(suffix)
391
+
392
+ @staticmethod
393
+ def contains(s: str, substring: str) -> bool:
394
+ """判断字符串是否包含指定子串
395
+
396
+ Args:
397
+ s: 字符串
398
+ substring: 子串
399
+
400
+ Returns:
401
+ bool: 是否包含指定子串
402
+ """
403
+ if s is None or substring is None:
404
+ return False
405
+ return substring in s
406
+
407
+ @staticmethod
408
+ def substring(s: str, start: int, length: int = None) -> str:
409
+ """截取子串
410
+
411
+ Args:
412
+ s: 字符串
413
+ start: 起始位置
414
+ length: 截取长度,默认为到字符串末尾
415
+
416
+ Returns:
417
+ str: 截取的子串
418
+ """
419
+ if s is None:
420
+ return ""
421
+ if length is None:
422
+ return s[start:]
423
+ return s[start:start + length]
424
+
425
+ @staticmethod
426
+ def is_integer(value: Any) -> bool:
427
+ """判断是否为整数
428
+
429
+ Args:
430
+ value: 任意值
431
+
432
+ Returns:
433
+ bool: 是否为整数
434
+ """
435
+ return isinstance(value, int)
436
+
437
+ @staticmethod
438
+ def is_float(value: Any) -> bool:
439
+ """判断是否为浮点数
440
+
441
+ Args:
442
+ value: 任意值
443
+
444
+ Returns:
445
+ bool: 是否为浮点数
446
+ """
447
+ return isinstance(value, float)
448
+
449
+ @staticmethod
450
+ def in_range(value: Union[int, float], min_value: Union[int, float], max_value: Union[int, float]) -> bool:
451
+ """判断值是否在指定范围内
452
+
453
+ Args:
454
+ value: 要判断的值
455
+ min_value: 最小值
456
+ max_value: 最大值
457
+
458
+ Returns:
459
+ bool: 是否在范围内
460
+ """
461
+ return min_value <= value <= max_value
462
+
463
+ @staticmethod
464
+ def is_list(value: Any) -> bool:
465
+ """判断是否为列表
466
+
467
+ Args:
468
+ value: 任意值
469
+
470
+ Returns:
471
+ bool: 是否为列表
472
+ """
473
+ return isinstance(value, list)
474
+
475
+ @staticmethod
476
+ def get_first(lst: List[Any], default: Any = None) -> Any:
477
+ """获取列表第一个元素
478
+
479
+ Args:
480
+ lst: 列表
481
+ default: 默认值
482
+
483
+ Returns:
484
+ Any: 第一个元素或默认值
485
+ """
486
+ if lst is None or not isinstance(lst, list) or len(lst) == 0:
487
+ return default
488
+ return lst[0]
489
+
490
+ @staticmethod
491
+ def get_last(lst: List[Any], default: Any = None) -> Any:
492
+ """获取列表最后一个元素
493
+
494
+ Args:
495
+ lst: 列表
496
+ default: 默认值
497
+
498
+ Returns:
499
+ Any: 最后一个元素或默认值
500
+ """
501
+ if lst is None or not isinstance(lst, list) or len(lst) == 0:
502
+ return default
503
+ return lst[-1]
504
+
505
+ @staticmethod
506
+ def chunk(lst: List[Any], size: int) -> List[List[Any]]:
507
+ """将列表分割为指定大小的块
508
+
509
+ Args:
510
+ lst: 列表
511
+ size: 块大小
512
+
513
+ Returns:
514
+ List[List[Any]]: 分割后的列表
515
+ """
516
+ if lst is None or not isinstance(lst, list) or size <= 0:
517
+ return []
518
+ return [lst[i:i + size] for i in range(0, len(lst), size)]
519
+
520
+ @staticmethod
521
+ def is_dict(value: Any) -> bool:
522
+ """判断是否为字典
523
+
524
+ Args:
525
+ value: 任意值
526
+
527
+ Returns:
528
+ bool: 是否为字典
529
+ """
530
+ return isinstance(value, dict)
531
+
532
+ @staticmethod
533
+ def get_value(dictionary: Dict[str, Any], key: str, default: Any = None) -> Any:
534
+ """获取字典值
535
+
536
+ Args:
537
+ dictionary: 字典
538
+ key: 键
539
+ default: 默认值
540
+
541
+ Returns:
542
+ Any: 对应的值或默认值
543
+ """
544
+ if dictionary is None or not isinstance(dictionary, dict):
545
+ return default
546
+ return dictionary.get(key, default)
547
+
548
+ @staticmethod
549
+ def has_key(dictionary: Dict[str, Any], key: str) -> bool:
550
+ """判断字典是否包含指定键
551
+
552
+ Args:
553
+ dictionary: 字典
554
+ key: 键
555
+
556
+ Returns:
557
+ bool: 是否包含指定键
558
+ """
559
+ if dictionary is None or not isinstance(dictionary, dict) or key is None:
560
+ return False
561
+ return key in dictionary
562
+
563
+ @staticmethod
564
+ def is_collection(value: Any) -> bool:
565
+ """判断是否为集合类型(列表、元组、集合),不包括字符串和字典
566
+
567
+ Args:
568
+ value: 任意值
569
+
570
+ Returns:
571
+ bool: 是否为集合类型
572
+ """
573
+ return isinstance(value, (list, tuple, set))
574
+
575
+ @staticmethod
576
+ def count(lst: List[Any], value: Any) -> int:
577
+ """统计列表中指定元素出现的次数
578
+
579
+ Args:
580
+ lst: 列表
581
+ value: 要统计的元素
582
+
583
+ Returns:
584
+ int: 出现次数
585
+ """
586
+ if lst is None or not isinstance(lst, list):
587
+ return 0
588
+ return lst.count(value)
@@ -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