crawlo 1.1.3__py3-none-any.whl → 1.1.5__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 crawlo might be problematic. Click here for more details.

Files changed (115) hide show
  1. crawlo/__init__.py +28 -1
  2. crawlo/__version__.py +1 -1
  3. crawlo/cleaners/__init__.py +61 -0
  4. crawlo/cleaners/data_formatter.py +226 -0
  5. crawlo/cleaners/encoding_converter.py +126 -0
  6. crawlo/cleaners/text_cleaner.py +233 -0
  7. crawlo/commands/startproject.py +117 -13
  8. crawlo/config.py +30 -0
  9. crawlo/config_validator.py +253 -0
  10. crawlo/core/engine.py +185 -11
  11. crawlo/core/scheduler.py +49 -78
  12. crawlo/crawler.py +6 -6
  13. crawlo/downloader/__init__.py +24 -0
  14. crawlo/downloader/aiohttp_downloader.py +8 -0
  15. crawlo/downloader/cffi_downloader.py +5 -0
  16. crawlo/downloader/hybrid_downloader.py +214 -0
  17. crawlo/downloader/playwright_downloader.py +403 -0
  18. crawlo/downloader/selenium_downloader.py +473 -0
  19. crawlo/extension/__init__.py +17 -10
  20. crawlo/extension/health_check.py +142 -0
  21. crawlo/extension/log_interval.py +27 -18
  22. crawlo/extension/log_stats.py +62 -24
  23. crawlo/extension/logging_extension.py +18 -9
  24. crawlo/extension/memory_monitor.py +105 -0
  25. crawlo/extension/performance_profiler.py +134 -0
  26. crawlo/extension/request_recorder.py +108 -0
  27. crawlo/filters/aioredis_filter.py +50 -12
  28. crawlo/middleware/proxy.py +26 -2
  29. crawlo/mode_manager.py +24 -19
  30. crawlo/network/request.py +30 -3
  31. crawlo/network/response.py +114 -25
  32. crawlo/pipelines/mongo_pipeline.py +81 -66
  33. crawlo/pipelines/mysql_pipeline.py +165 -43
  34. crawlo/pipelines/redis_dedup_pipeline.py +7 -3
  35. crawlo/queue/queue_manager.py +15 -2
  36. crawlo/queue/redis_priority_queue.py +144 -76
  37. crawlo/settings/default_settings.py +93 -121
  38. crawlo/subscriber.py +62 -37
  39. crawlo/templates/project/items.py.tmpl +1 -1
  40. crawlo/templates/project/middlewares.py.tmpl +73 -49
  41. crawlo/templates/project/pipelines.py.tmpl +51 -295
  42. crawlo/templates/project/settings.py.tmpl +93 -17
  43. crawlo/templates/project/settings_distributed.py.tmpl +120 -0
  44. crawlo/templates/project/settings_gentle.py.tmpl +95 -0
  45. crawlo/templates/project/settings_high_performance.py.tmpl +152 -0
  46. crawlo/templates/project/settings_simple.py.tmpl +69 -0
  47. crawlo/templates/spider/spider.py.tmpl +2 -38
  48. crawlo/tools/__init__.py +183 -0
  49. crawlo/tools/anti_crawler.py +269 -0
  50. crawlo/tools/authenticated_proxy.py +241 -0
  51. crawlo/tools/data_validator.py +181 -0
  52. crawlo/tools/date_tools.py +36 -0
  53. crawlo/tools/distributed_coordinator.py +387 -0
  54. crawlo/tools/retry_mechanism.py +221 -0
  55. crawlo/tools/scenario_adapter.py +263 -0
  56. crawlo/utils/__init__.py +29 -1
  57. crawlo/utils/batch_processor.py +261 -0
  58. crawlo/utils/date_tools.py +58 -1
  59. crawlo/utils/enhanced_error_handler.py +360 -0
  60. crawlo/utils/env_config.py +106 -0
  61. crawlo/utils/error_handler.py +126 -0
  62. crawlo/utils/performance_monitor.py +285 -0
  63. crawlo/utils/redis_connection_pool.py +335 -0
  64. crawlo/utils/redis_key_validator.py +200 -0
  65. crawlo-1.1.5.dist-info/METADATA +401 -0
  66. crawlo-1.1.5.dist-info/RECORD +185 -0
  67. tests/advanced_tools_example.py +276 -0
  68. tests/authenticated_proxy_example.py +237 -0
  69. tests/cleaners_example.py +161 -0
  70. tests/config_validation_demo.py +103 -0
  71. tests/date_tools_example.py +181 -0
  72. tests/dynamic_loading_example.py +524 -0
  73. tests/dynamic_loading_test.py +105 -0
  74. tests/env_config_example.py +134 -0
  75. tests/error_handling_example.py +172 -0
  76. tests/redis_key_validation_demo.py +131 -0
  77. tests/response_improvements_example.py +145 -0
  78. tests/test_advanced_tools.py +149 -0
  79. tests/test_all_redis_key_configs.py +146 -0
  80. tests/test_authenticated_proxy.py +142 -0
  81. tests/test_cleaners.py +55 -0
  82. tests/test_comprehensive.py +147 -0
  83. tests/test_config_validator.py +194 -0
  84. tests/test_date_tools.py +124 -0
  85. tests/test_dynamic_downloaders_proxy.py +125 -0
  86. tests/test_dynamic_proxy.py +93 -0
  87. tests/test_dynamic_proxy_config.py +147 -0
  88. tests/test_dynamic_proxy_real.py +110 -0
  89. tests/test_edge_cases.py +304 -0
  90. tests/test_enhanced_error_handler.py +271 -0
  91. tests/test_env_config.py +122 -0
  92. tests/test_error_handler_compatibility.py +113 -0
  93. tests/test_framework_env_usage.py +104 -0
  94. tests/test_integration.py +357 -0
  95. tests/test_item_dedup_redis_key.py +123 -0
  96. tests/test_parsel.py +30 -0
  97. tests/test_performance.py +328 -0
  98. tests/test_queue_manager_redis_key.py +177 -0
  99. tests/test_redis_connection_pool.py +295 -0
  100. tests/test_redis_key_naming.py +182 -0
  101. tests/test_redis_key_validator.py +124 -0
  102. tests/test_response_improvements.py +153 -0
  103. tests/test_simple_response.py +62 -0
  104. tests/test_telecom_spider_redis_key.py +206 -0
  105. tests/test_template_content.py +88 -0
  106. tests/test_template_redis_key.py +135 -0
  107. tests/test_tools.py +154 -0
  108. tests/tools_example.py +258 -0
  109. crawlo/core/enhanced_engine.py +0 -190
  110. crawlo-1.1.3.dist-info/METADATA +0 -635
  111. crawlo-1.1.3.dist-info/RECORD +0 -113
  112. {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/WHEEL +0 -0
  113. {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/entry_points.txt +0 -0
  114. {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/top_level.txt +0 -0
  115. {examples → tests}/controlled_spider_example.py +0 -0
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ 场景适配器
5
+ =========
6
+ 根据不同的动态加载场景,自动配置和优化下载器选择策略。
7
+
8
+ 支持的场景:
9
+ 1. 列表页、详情页都要动态加载
10
+ 2. 列表页使用协议请求、详情页使用动态加载
11
+ 3. 列表页使用动态加载,详情页使用协议请求
12
+
13
+ 使用示例:
14
+ # 场景1: 全动态加载
15
+ adapter = DynamicLoadingScenarioAdapter(scenario="all_dynamic")
16
+
17
+ # 场景2: 列表页协议,详情页动态
18
+ adapter = DynamicLoadingScenarioAdapter(scenario="list_protocol_detail_dynamic")
19
+
20
+ # 场景3: 列表页动态,详情页协议
21
+ adapter = DynamicLoadingScenarioAdapter(scenario="list_dynamic_detail_protocol")
22
+ """
23
+ import re
24
+ from typing import Dict, Any
25
+ from urllib.parse import urlparse
26
+
27
+ from crawlo.utils.log import get_logger
28
+
29
+
30
+ class DynamicLoadingScenarioAdapter:
31
+ """
32
+ 动态加载场景适配器
33
+ 根据不同的业务场景自动配置下载器选择策略
34
+ """
35
+
36
+ SCENARIOS = {
37
+ "all_dynamic": "列表页、详情页都要动态加载",
38
+ "list_protocol_detail_dynamic": "列表页使用协议请求、详情页使用动态加载",
39
+ "list_dynamic_detail_protocol": "列表页使用动态加载,详情页使用协议请求"
40
+ }
41
+
42
+ def __init__(self, scenario: str = "list_protocol_detail_dynamic", **kwargs):
43
+ """
44
+ 初始化场景适配器
45
+
46
+ :param scenario: 场景类型
47
+ :param kwargs: 其他配置参数
48
+ """
49
+ self.scenario = scenario
50
+ self.logger = get_logger(self.__class__.__name__)
51
+
52
+ # 验证场景类型
53
+ if scenario not in self.SCENARIOS:
54
+ raise ValueError(f"Unsupported scenario: {scenario}. Supported: {list(self.SCENARIOS.keys())}")
55
+
56
+ self.logger.info(f"Initializing DynamicLoadingScenarioAdapter for scenario: {scenario}")
57
+
58
+ # 配置参数
59
+ self.list_page_patterns = kwargs.get("list_page_patterns", [
60
+ r"/list", r"/search", r"/category", r"/page/\d+", r"\?page=", r"\?p=\d+"
61
+ ])
62
+
63
+ self.detail_page_patterns = kwargs.get("detail_page_patterns", [
64
+ r"/detail", r"/item", r"/product", r"/article", r"/post", r"/view", r"/\d+"
65
+ ])
66
+
67
+ self.list_domains = set(kwargs.get("list_domains", []))
68
+ self.detail_domains = set(kwargs.get("detail_domains", []))
69
+
70
+ # 构建配置
71
+ self.config = self._build_config()
72
+
73
+ def _build_config(self) -> Dict[str, Any]:
74
+ """根据场景构建配置"""
75
+ config = {
76
+ "HYBRID_DYNAMIC_URL_PATTERNS": [],
77
+ "HYBRID_PROTOCOL_URL_PATTERNS": [],
78
+ "HYBRID_DYNAMIC_DOMAINS": [],
79
+ "HYBRID_PROTOCOL_DOMAINS": []
80
+ }
81
+
82
+ if self.scenario == "all_dynamic":
83
+ # 所有页面都使用动态加载
84
+ config["HYBRID_DYNAMIC_URL_PATTERNS"].extend(self.list_page_patterns)
85
+ config["HYBRID_DYNAMIC_URL_PATTERNS"].extend(self.detail_page_patterns)
86
+
87
+ elif self.scenario == "list_protocol_detail_dynamic":
88
+ # 列表页使用协议请求,详情页使用动态加载
89
+ config["HYBRID_PROTOCOL_URL_PATTERNS"].extend(self.list_page_patterns)
90
+ config["HYBRID_DYNAMIC_URL_PATTERNS"].extend(self.detail_page_patterns)
91
+
92
+ # 域名配置
93
+ config["HYBRID_PROTOCOL_DOMAINS"].extend(self.list_domains)
94
+ config["HYBRID_DYNAMIC_DOMAINS"].extend(self.detail_domains)
95
+
96
+ elif self.scenario == "list_dynamic_detail_protocol":
97
+ # 列表页使用动态加载,详情页使用协议请求
98
+ config["HYBRID_DYNAMIC_URL_PATTERNS"].extend(self.list_page_patterns)
99
+ config["HYBRID_PROTOCOL_URL_PATTERNS"].extend(self.detail_page_patterns)
100
+
101
+ # 域名配置
102
+ config["HYBRID_DYNAMIC_DOMAINS"].extend(self.list_domains)
103
+ config["HYBRID_PROTOCOL_DOMAINS"].extend(self.detail_domains)
104
+
105
+ return config
106
+
107
+ def get_settings(self) -> Dict[str, Any]:
108
+ """获取场景配置设置"""
109
+ return self.config
110
+
111
+ def should_use_dynamic_loader(self, url: str) -> bool:
112
+ """
113
+ 判断给定URL是否应该使用动态加载器
114
+
115
+ :param url: 要判断的URL
116
+ :return: 是否使用动态加载器
117
+ """
118
+ parsed_url = urlparse(url)
119
+ domain = parsed_url.netloc.lower()
120
+ path = parsed_url.path.lower()
121
+ query = parsed_url.query.lower()
122
+ full_path = path + ("?" + query if query else "")
123
+
124
+ # 检查域名
125
+ if domain in self.config["HYBRID_DYNAMIC_DOMAINS"]:
126
+ return True
127
+ if domain in self.config["HYBRID_PROTOCOL_DOMAINS"]:
128
+ return False
129
+
130
+ # 检查URL模式
131
+ # 检查动态模式
132
+ for pattern in self.config["HYBRID_DYNAMIC_URL_PATTERNS"]:
133
+ if re.search(pattern, full_path):
134
+ return True
135
+
136
+ # 检查协议模式
137
+ for pattern in self.config["HYBRID_PROTOCOL_URL_PATTERNS"]:
138
+ if re.search(pattern, full_path):
139
+ return False
140
+
141
+ # 默认策略
142
+ if self.scenario == "all_dynamic":
143
+ return True
144
+ elif self.scenario == "list_protocol_detail_dynamic":
145
+ # 默认详情页使用动态加载
146
+ return True
147
+ elif self.scenario == "list_dynamic_detail_protocol":
148
+ # 默认详情页使用协议加载
149
+ return False
150
+
151
+ # 默认返回False(使用协议加载器)
152
+ return False
153
+
154
+ def get_loader_options(self, url: str) -> Dict[str, Any]:
155
+ """
156
+ 获取特定URL的加载器选项
157
+
158
+ :param url: URL
159
+ :return: 加载器选项
160
+ """
161
+ options = {}
162
+
163
+ # 可以根据URL添加特定的加载器选项
164
+ # 例如,对于某些页面可能需要等待特定元素加载完成
165
+ if "product" in url:
166
+ options["wait_for_element"] = ".product-detail"
167
+ elif "article" in url:
168
+ options["wait_for_element"] = ".article-content"
169
+
170
+ return options
171
+
172
+ def adapt_request(self, request) -> None:
173
+ """
174
+ 适配请求对象,根据场景自动设置加载器
175
+
176
+ :param request: 请求对象
177
+ """
178
+ use_dynamic = self.should_use_dynamic_loader(request.url)
179
+
180
+ if use_dynamic:
181
+ request.set_dynamic_loader(True, self.get_loader_options(request.url))
182
+ self.logger.debug(f"Adapted request {request.url} to use dynamic loader")
183
+ else:
184
+ request.set_protocol_loader()
185
+ self.logger.debug(f"Adapted request {request.url} to use protocol loader")
186
+
187
+
188
+ # 便利函数
189
+ def create_scenario_adapter(scenario: str = "list_protocol_detail_dynamic", **kwargs):
190
+ """
191
+ 创建场景适配器的便利函数
192
+
193
+ :param scenario: 场景类型
194
+ :param kwargs: 其他配置参数
195
+ :return: 场景适配器实例
196
+ """
197
+ return DynamicLoadingScenarioAdapter(scenario, **kwargs)
198
+
199
+
200
+ def get_scenario_settings(scenario: str = "list_protocol_detail_dynamic", **kwargs) -> Dict[str, Any]:
201
+ """
202
+ 获取场景配置设置的便利函数
203
+
204
+ :param scenario: 场景类型
205
+ :param kwargs: 其他配置参数
206
+ :return: 配置设置字典
207
+ """
208
+ adapter = DynamicLoadingScenarioAdapter(scenario, **kwargs)
209
+ return adapter.get_settings()
210
+
211
+
212
+ # 预定义场景配置
213
+ SCENARIO_CONFIGS = {
214
+ "电商网站": {
215
+ "scenario": "list_protocol_detail_dynamic",
216
+ "list_page_patterns": [r"/list", r"/search", r"/category", r"/page/\d+"],
217
+ "detail_page_patterns": [r"/product", r"/item", r"/detail/\d+"],
218
+ "list_domains": [],
219
+ "detail_domains": []
220
+ },
221
+
222
+ "新闻网站": {
223
+ "scenario": "list_protocol_detail_dynamic",
224
+ "list_page_patterns": [r"/list", r"/category", r"/page/\d+"],
225
+ "detail_page_patterns": [r"/article", r"/post", r"/news/\d+"],
226
+ "list_domains": [],
227
+ "detail_domains": []
228
+ },
229
+
230
+ "社交平台": {
231
+ "scenario": "all_dynamic",
232
+ "list_page_patterns": [r"/feed", r"/timeline", r"/explore"],
233
+ "detail_page_patterns": [r"/post", r"/status", r"/photo"],
234
+ "list_domains": [],
235
+ "detail_domains": []
236
+ },
237
+
238
+ "博客平台": {
239
+ "scenario": "list_dynamic_detail_protocol",
240
+ "list_page_patterns": [r"/blog", r"/posts", r"/archive"],
241
+ "detail_page_patterns": [r"/\d{4}/\d{2}/\d{2}/"],
242
+ "list_domains": [],
243
+ "detail_domains": []
244
+ }
245
+ }
246
+
247
+
248
+ def create_adapter_for_platform(platform: str, **custom_kwargs) -> DynamicLoadingScenarioAdapter:
249
+ """
250
+ 为特定平台创建场景适配器
251
+
252
+ :param platform: 平台名称
253
+ :param custom_kwargs: 自定义配置参数
254
+ :return: 场景适配器实例
255
+ """
256
+ if platform not in SCENARIO_CONFIGS:
257
+ raise ValueError(f"Unsupported platform: {platform}. Supported: {list(SCENARIO_CONFIGS.keys())}")
258
+
259
+ config = SCENARIO_CONFIGS[platform].copy()
260
+ config.update(custom_kwargs)
261
+ scenario = config.pop("scenario")
262
+
263
+ return DynamicLoadingScenarioAdapter(scenario, **config)
crawlo/utils/__init__.py CHANGED
@@ -3,5 +3,33 @@
3
3
  """
4
4
  # @Time : 2025-02-05 13:57
5
5
  # @Author : oscar
6
- # @Desc : None
6
+ # @Desc : 工具模块集合
7
7
  """
8
+
9
+ from .date_tools import (
10
+ TimeUtils,
11
+ parse_time,
12
+ format_time,
13
+ time_diff,
14
+ to_timestamp,
15
+ to_datetime,
16
+ now,
17
+ to_timezone,
18
+ to_utc,
19
+ to_local,
20
+ from_timestamp_with_tz
21
+ )
22
+
23
+ __all__ = [
24
+ "TimeUtils",
25
+ "parse_time",
26
+ "format_time",
27
+ "time_diff",
28
+ "to_timestamp",
29
+ "to_datetime",
30
+ "now",
31
+ "to_timezone",
32
+ "to_utc",
33
+ "to_local",
34
+ "from_timestamp_with_tz"
35
+ ]
@@ -0,0 +1,261 @@
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ """
4
+ 批处理操作工具
5
+ 提供批量操作的统一接口和优化实现
6
+ """
7
+ import asyncio
8
+ import time
9
+ from typing import List, Callable, Any, Optional, Dict
10
+ from functools import wraps
11
+
12
+ from crawlo.utils.log import get_logger
13
+ from crawlo.utils.error_handler import ErrorHandler
14
+
15
+
16
+ class BatchProcessor:
17
+ """批处理处理器"""
18
+
19
+ def __init__(self, batch_size: int = 100, max_concurrent_batches: int = 5):
20
+ self.batch_size = batch_size
21
+ self.max_concurrent_batches = max_concurrent_batches
22
+ self.logger = get_logger(self.__class__.__name__)
23
+ self.error_handler = ErrorHandler(self.__class__.__name__)
24
+
25
+ async def process_batch(self, items: List[Any], processor_func: Callable,
26
+ *args, **kwargs) -> List[Any]:
27
+ """
28
+ 处理一批数据项
29
+
30
+ Args:
31
+ items: 要处理的数据项列表
32
+ processor_func: 处理函数
33
+ *args: 传递给处理函数的额外参数
34
+ **kwargs: 传递给处理函数的关键字参数
35
+
36
+ Returns:
37
+ 处理结果列表
38
+ """
39
+ results = []
40
+ semaphore = asyncio.Semaphore(self.max_concurrent_batches)
41
+
42
+ async def process_item(item):
43
+ async with semaphore:
44
+ try:
45
+ if asyncio.iscoroutinefunction(processor_func):
46
+ return await processor_func(item, *args, **kwargs)
47
+ else:
48
+ return processor_func(item, *args, **kwargs)
49
+ except Exception as e:
50
+ self.logger.error(f"处理单项失败: {e}")
51
+ return None
52
+
53
+ # 并发处理批次中的所有项
54
+ tasks = [process_item(item) for item in items]
55
+ results = await asyncio.gather(*tasks, return_exceptions=True)
56
+
57
+ # 过滤掉异常结果
58
+ return [result for result in results if not isinstance(result, Exception)]
59
+
60
+ async def process_in_batches(self, items: List[Any], processor_func: Callable,
61
+ *args, **kwargs) -> List[Any]:
62
+ """
63
+ 分批处理大量数据项
64
+
65
+ Args:
66
+ items: 要处理的数据项列表
67
+ processor_func: 处理函数
68
+ *args: 传递给处理函数的额外参数
69
+ **kwargs: 传递给处理函数的关键字参数
70
+
71
+ Returns:
72
+ 所有处理结果的列表
73
+ """
74
+ all_results = []
75
+
76
+ # 将数据分批处理
77
+ for i in range(0, len(items), self.batch_size):
78
+ batch = items[i:i + self.batch_size]
79
+ self.logger.debug(f"处理批次 {i//self.batch_size + 1}/{(len(items)-1)//self.batch_size + 1}")
80
+
81
+ try:
82
+ batch_results = await self.process_batch(batch, processor_func, *args, **kwargs)
83
+ all_results.extend(batch_results)
84
+ except Exception as e:
85
+ self.logger.error(f"处理批次失败: {e}")
86
+ # 继续处理下一个批次而不是中断
87
+
88
+ return all_results
89
+
90
+ def batch_process_decorator(self, batch_size: Optional[int] = None):
91
+ """
92
+ 装饰器:将函数转换为批处理函数
93
+
94
+ Args:
95
+ batch_size: 批次大小(如果为None则使用实例的batch_size)
96
+ """
97
+ def decorator(func):
98
+ @wraps(func)
99
+ async def async_wrapper(items: List[Any], *args, **kwargs):
100
+ actual_batch_size = batch_size or self.batch_size
101
+ processor = BatchProcessor(actual_batch_size, self.max_concurrent_batches)
102
+ return await processor.process_in_batches(items, func, *args, **kwargs)
103
+
104
+ @wraps(func)
105
+ def sync_wrapper(items: List[Any], *args, **kwargs):
106
+ # 同步版本使用事件循环运行异步函数
107
+ return asyncio.run(async_wrapper(items, *args, **kwargs))
108
+
109
+ # 根据原函数是否为异步函数返回相应的包装器
110
+ import inspect
111
+ if inspect.iscoroutinefunction(func):
112
+ return async_wrapper
113
+ else:
114
+ return sync_wrapper
115
+
116
+ return decorator
117
+
118
+
119
+ class RedisBatchProcessor:
120
+ """Redis批处理处理器"""
121
+
122
+ def __init__(self, redis_client, batch_size: int = 100):
123
+ self.redis_client = redis_client
124
+ self.batch_size = batch_size
125
+ self.logger = get_logger(self.__class__.__name__)
126
+ self.error_handler = ErrorHandler(self.__class__.__name__)
127
+
128
+ async def batch_set(self, items: List[Dict[str, Any]]) -> int:
129
+ """
130
+ 批量设置Redis键值对
131
+
132
+ Args:
133
+ items: 包含key和value的字典列表
134
+
135
+ Returns:
136
+ 成功设置的键值对数量
137
+ """
138
+ try:
139
+ pipe = self.redis_client.pipeline()
140
+ count = 0
141
+
142
+ for item in items:
143
+ if 'key' in item and 'value' in item:
144
+ pipe.set(item['key'], item['value'])
145
+ count += 1
146
+
147
+ # 每达到批次大小就执行一次
148
+ if count % self.batch_size == 0:
149
+ await pipe.execute()
150
+ pipe = self.redis_client.pipeline()
151
+
152
+ # 执行剩余的操作
153
+ if count % self.batch_size != 0:
154
+ await pipe.execute()
155
+
156
+ self.logger.debug(f"批量设置 {count} 个键值对")
157
+ return count
158
+ except Exception as e:
159
+ self.error_handler.handle_error(
160
+ e,
161
+ context="Redis批量设置失败",
162
+ raise_error=False
163
+ )
164
+ return 0
165
+
166
+ async def batch_get(self, keys: List[str]) -> Dict[str, Any]:
167
+ """
168
+ 批量获取Redis键值
169
+
170
+ Args:
171
+ keys: 要获取的键列表
172
+
173
+ Returns:
174
+ 键值对字典
175
+ """
176
+ try:
177
+ # 使用管道批量获取
178
+ pipe = self.redis_client.pipeline()
179
+ for key in keys:
180
+ pipe.get(key)
181
+
182
+ results = await pipe.execute()
183
+
184
+ # 构建结果字典
185
+ result_dict = {}
186
+ for i, key in enumerate(keys):
187
+ if results[i] is not None:
188
+ result_dict[key] = results[i]
189
+
190
+ self.logger.debug(f"批量获取 {len(result_dict)} 个键值对")
191
+ return result_dict
192
+ except Exception as e:
193
+ self.error_handler.handle_error(
194
+ e,
195
+ context="Redis批量获取失败",
196
+ raise_error=False
197
+ )
198
+ return {}
199
+
200
+ async def batch_delete(self, keys: List[str]) -> int:
201
+ """
202
+ 批量删除Redis键
203
+
204
+ Args:
205
+ keys: 要删除的键列表
206
+
207
+ Returns:
208
+ 成功删除的键数量
209
+ """
210
+ try:
211
+ pipe = self.redis_client.pipeline()
212
+ count = 0
213
+
214
+ for key in keys:
215
+ pipe.delete(key)
216
+ count += 1
217
+
218
+ # 每达到批次大小就执行一次
219
+ if count % self.batch_size == 0:
220
+ await pipe.execute()
221
+ pipe = self.redis_client.pipeline()
222
+
223
+ # 执行剩余的操作
224
+ if count % self.batch_size != 0:
225
+ await pipe.execute()
226
+
227
+ self.logger.debug(f"批量删除 {count} 个键")
228
+ return count
229
+ except Exception as e:
230
+ self.error_handler.handle_error(
231
+ e,
232
+ context="Redis批量删除失败",
233
+ raise_error=False
234
+ )
235
+ return 0
236
+
237
+
238
+ # 全局批处理器实例
239
+ default_batch_processor = BatchProcessor()
240
+
241
+
242
+ def batch_process(items: List[Any], processor_func: Callable,
243
+ batch_size: int = 100, max_concurrent_batches: int = 5,
244
+ *args, **kwargs) -> List[Any]:
245
+ """
246
+ 便捷函数:批处理数据项
247
+
248
+ Args:
249
+ items: 要处理的数据项列表
250
+ processor_func: 处理函数
251
+ batch_size: 批次大小
252
+ max_concurrent_batches: 最大并发批次数量
253
+ *args: 传递给处理函数的额外参数
254
+ **kwargs: 传递给处理函数的关键字参数
255
+
256
+ Returns:
257
+ 所有处理结果的列表
258
+ """
259
+ processor = BatchProcessor(batch_size, max_concurrent_batches)
260
+ import asyncio
261
+ return asyncio.run(processor.process_in_batches(items, processor_func, *args, **kwargs))
@@ -7,13 +7,17 @@
7
7
  """
8
8
  import dateparser
9
9
  from typing import Optional, Union, Literal
10
- from datetime import datetime, timedelta
10
+ from datetime import datetime, timedelta, timezone
11
11
  from dateutil.relativedelta import relativedelta
12
+ import pytz
13
+ from pytz import timezone as pytz_timezone
12
14
 
13
15
  # 支持的单位类型
14
16
  TimeUnit = Literal["seconds", "minutes", "hours", "days"]
15
17
  # 时间输入类型
16
18
  TimeType = Union[str, datetime]
19
+ # 时区类型
20
+ TimezoneType = Union[str, timezone, pytz_timezone]
17
21
 
18
22
  # 常见时间格式列表(作为 dateparser 的后备方案)
19
23
  COMMON_FORMATS = [
@@ -195,6 +199,43 @@ class TimeUtils:
195
199
  return None
196
200
  return dt.isoformat()
197
201
 
202
+ @classmethod
203
+ def to_timezone(cls, dt: TimeType, tz: TimezoneType) -> Optional[datetime]:
204
+ """将时间转换为指定时区"""
205
+ dt = cls.parse(dt)
206
+ if dt is None:
207
+ return None
208
+
209
+ try:
210
+ if isinstance(tz, str):
211
+ tz = pytz_timezone(tz)
212
+ return dt.astimezone(tz)
213
+ except Exception:
214
+ return None
215
+
216
+ @classmethod
217
+ def to_utc(cls, dt: TimeType) -> Optional[datetime]:
218
+ """将时间转换为 UTC 时区"""
219
+ return cls.to_timezone(dt, pytz.UTC)
220
+
221
+ @classmethod
222
+ def to_local(cls, dt: TimeType) -> Optional[datetime]:
223
+ """将时间转换为本地时区"""
224
+ return cls.to_timezone(dt, pytz.timezone("Asia/Shanghai"))
225
+
226
+ @classmethod
227
+ def from_timestamp_with_tz(cls, ts: float, tz: TimezoneType = None) -> Optional[datetime]:
228
+ """从时间戳创建 datetime,并可选择指定时区"""
229
+ try:
230
+ dt = datetime.fromtimestamp(ts)
231
+ if tz:
232
+ if isinstance(tz, str):
233
+ tz = pytz_timezone(tz)
234
+ dt = dt.replace(tzinfo=tz)
235
+ return dt
236
+ except Exception:
237
+ return None
238
+
198
239
 
199
240
  # =======================对外接口=======================
200
241
 
@@ -227,6 +268,22 @@ def now(fmt: Optional[str] = None) -> Union[datetime, str]:
227
268
  """获取当前时间"""
228
269
  return TimeUtils.now(fmt)
229
270
 
271
+ def to_timezone(dt: TimeType, tz: TimezoneType) -> Optional[datetime]:
272
+ """将时间转换为指定时区"""
273
+ return TimeUtils.to_timezone(dt, tz)
274
+
275
+ def to_utc(dt: TimeType) -> Optional[datetime]:
276
+ """将时间转换为 UTC 时区"""
277
+ return TimeUtils.to_utc(dt)
278
+
279
+ def to_local(dt: TimeType) -> Optional[datetime]:
280
+ """将时间转换为本地时区"""
281
+ return TimeUtils.to_local(dt)
282
+
283
+ def from_timestamp_with_tz(ts: float, tz: TimezoneType = None) -> Optional[datetime]:
284
+ """从时间戳创建 datetime,并可选择指定时区"""
285
+ return TimeUtils.from_timestamp_with_tz(ts, tz)
286
+
230
287
 
231
288
  if __name__ == '__main__':
232
289
  get_current_time = now(fmt="%Y-%m-%d %H:%M:%S")