crawlo 1.4.4__py3-none-any.whl → 1.4.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 (85) hide show
  1. crawlo/__init__.py +11 -15
  2. crawlo/__version__.py +1 -1
  3. crawlo/commands/startproject.py +24 -0
  4. crawlo/core/engine.py +2 -2
  5. crawlo/core/scheduler.py +4 -4
  6. crawlo/crawler.py +8 -7
  7. crawlo/downloader/__init__.py +5 -2
  8. crawlo/extension/__init__.py +2 -2
  9. crawlo/filters/aioredis_filter.py +8 -1
  10. crawlo/filters/memory_filter.py +8 -1
  11. crawlo/initialization/built_in.py +13 -4
  12. crawlo/initialization/core.py +5 -4
  13. crawlo/interfaces.py +24 -0
  14. crawlo/middleware/__init__.py +7 -4
  15. crawlo/middleware/middleware_manager.py +15 -8
  16. crawlo/mode_manager.py +45 -11
  17. crawlo/network/response.py +374 -69
  18. crawlo/pipelines/mysql_pipeline.py +6 -6
  19. crawlo/pipelines/pipeline_manager.py +2 -2
  20. crawlo/project.py +2 -4
  21. crawlo/settings/default_settings.py +4 -0
  22. crawlo/task_manager.py +2 -2
  23. crawlo/templates/project/items.py.tmpl +2 -2
  24. crawlo/templates/project/middlewares.py.tmpl +9 -89
  25. crawlo/templates/project/pipelines.py.tmpl +8 -68
  26. crawlo/tools/__init__.py +0 -11
  27. crawlo/utils/__init__.py +17 -1
  28. crawlo/utils/db_helper.py +220 -319
  29. crawlo/utils/error_handler.py +313 -67
  30. crawlo/utils/fingerprint.py +3 -4
  31. crawlo/utils/misc.py +82 -0
  32. crawlo/utils/request.py +55 -66
  33. crawlo/utils/selector_helper.py +138 -0
  34. crawlo/utils/spider_loader.py +185 -45
  35. crawlo/utils/text_helper.py +95 -0
  36. crawlo-1.4.5.dist-info/METADATA +329 -0
  37. {crawlo-1.4.4.dist-info → crawlo-1.4.5.dist-info}/RECORD +76 -49
  38. tests/bug_check_test.py +251 -0
  39. tests/direct_selector_helper_test.py +97 -0
  40. tests/ofweek_scrapy/ofweek_scrapy/items.py +12 -0
  41. tests/ofweek_scrapy/ofweek_scrapy/middlewares.py +100 -0
  42. tests/ofweek_scrapy/ofweek_scrapy/pipelines.py +13 -0
  43. tests/ofweek_scrapy/ofweek_scrapy/settings.py +85 -0
  44. tests/ofweek_scrapy/ofweek_scrapy/spiders/__init__.py +4 -0
  45. tests/ofweek_scrapy/ofweek_scrapy/spiders/ofweek_spider.py +162 -0
  46. tests/ofweek_scrapy/scrapy.cfg +11 -0
  47. tests/performance_comparison.py +4 -5
  48. tests/simple_crawlo_test.py +1 -2
  49. tests/simple_follow_test.py +39 -0
  50. tests/simple_response_selector_test.py +95 -0
  51. tests/simple_selector_helper_test.py +155 -0
  52. tests/simple_selector_test.py +208 -0
  53. tests/simple_url_test.py +74 -0
  54. tests/test_crawler_process_import.py +39 -0
  55. tests/test_crawler_process_spider_modules.py +48 -0
  56. tests/test_edge_cases.py +7 -5
  57. tests/test_encoding_core.py +57 -0
  58. tests/test_encoding_detection.py +127 -0
  59. tests/test_factory_compatibility.py +197 -0
  60. tests/test_optimized_selector_naming.py +101 -0
  61. tests/test_priority_behavior.py +18 -18
  62. tests/test_response_follow.py +105 -0
  63. tests/test_response_selector_methods.py +93 -0
  64. tests/test_response_url_methods.py +71 -0
  65. tests/test_response_urljoin.py +87 -0
  66. tests/test_scrapy_style_encoding.py +113 -0
  67. tests/test_selector_helper.py +101 -0
  68. tests/test_selector_optimizations.py +147 -0
  69. tests/test_spider_loader.py +50 -0
  70. tests/test_spider_loader_comprehensive.py +70 -0
  71. tests/test_spiders/__init__.py +1 -0
  72. tests/test_spiders/test_spider.py +10 -0
  73. crawlo/tools/anti_crawler.py +0 -269
  74. crawlo/utils/class_loader.py +0 -26
  75. crawlo/utils/enhanced_error_handler.py +0 -357
  76. crawlo-1.4.4.dist-info/METADATA +0 -190
  77. tests/simple_log_test.py +0 -58
  78. tests/simple_test.py +0 -48
  79. tests/test_framework_logger.py +0 -67
  80. tests/test_framework_startup.py +0 -65
  81. tests/test_mode_change.py +0 -73
  82. {crawlo-1.4.4.dist-info → crawlo-1.4.5.dist-info}/WHEEL +0 -0
  83. {crawlo-1.4.4.dist-info → crawlo-1.4.5.dist-info}/entry_points.txt +0 -0
  84. {crawlo-1.4.4.dist-info → crawlo-1.4.5.dist-info}/top_level.txt +0 -0
  85. /tests/{final_command_test_report.md → ofweek_scrapy/ofweek_scrapy/__init__.py} +0 -0
@@ -1,269 +0,0 @@
1
- #!/usr/bin/python
2
- # -*- coding: UTF-8 -*-
3
- """
4
- # @Time : 2025-09-10 22:00
5
- # @Author : crawl-coder
6
- # @Desc : 反爬虫应对工具
7
- """
8
-
9
- import asyncio
10
- import random
11
- import time
12
- from typing import Dict, Any, Optional, List, Callable
13
-
14
-
15
- class ProxyPoolManager:
16
- """代理池管理器类"""
17
-
18
- def __init__(self, proxies: Optional[List[Dict[str, str]]] = None):
19
- """
20
- 初始化代理池管理器
21
-
22
- Args:
23
- proxies (Optional[List[Dict[str, str]]]): 代理列表
24
- """
25
- self.proxies = proxies or [
26
- {"http": "http://proxy1.example.com:8080", "https": "https://proxy1.example.com:8080"},
27
- {"http": "http://proxy2.example.com:8080", "https": "https://proxy2.example.com:8080"},
28
- {"http": "http://proxy3.example.com:8080", "https": "https://proxy3.example.com:8080"}
29
- ]
30
- self.proxy_status = {id(proxy): {"last_used": 0, "success_count": 0, "fail_count": 0}
31
- for proxy in self.proxies}
32
-
33
- def get_random_proxy(self) -> Dict[str, str]:
34
- """
35
- 获取随机代理
36
-
37
- Returns:
38
- Dict[str, str]: 代理配置
39
- """
40
- return random.choice(self.proxies)
41
-
42
- def get_best_proxy(self) -> Dict[str, str]:
43
- """
44
- 根据成功率获取最佳代理
45
-
46
- Returns:
47
- Dict[str, str]: 代理配置
48
- """
49
- if not self.proxy_status:
50
- return self.get_random_proxy()
51
-
52
- # 计算每个代理的成功率
53
- proxy_scores = []
54
- for proxy in self.proxies:
55
- proxy_id = id(proxy)
56
- status = self.proxy_status.get(proxy_id, {"success_count": 0, "fail_count": 0})
57
- total = status["success_count"] + status["fail_count"]
58
-
59
- if total == 0:
60
- score = 0.5 # 默认成功率
61
- else:
62
- score = status["success_count"] / total
63
-
64
- proxy_scores.append((proxy, score))
65
-
66
- # 按成功率排序,返回成功率最高的代理
67
- proxy_scores.sort(key=lambda x: x[1], reverse=True)
68
- return proxy_scores[0][0]
69
-
70
- def report_proxy_result(self, proxy: Dict[str, str], success: bool) -> None:
71
- """
72
- 报告代理使用结果
73
-
74
- Args:
75
- proxy (Dict[str, str]): 代理配置
76
- success (bool): 是否成功
77
- """
78
- proxy_id = id(proxy)
79
- if proxy_id not in self.proxy_status:
80
- self.proxy_status[proxy_id] = {"last_used": 0, "success_count": 0, "fail_count": 0}
81
-
82
- status = self.proxy_status[proxy_id]
83
- status["last_used"] = time.time()
84
-
85
- if success:
86
- status["success_count"] += 1
87
- else:
88
- status["fail_count"] += 1
89
-
90
- def remove_invalid_proxy(self, proxy: Dict[str, str]) -> None:
91
- """
92
- 移除无效代理
93
-
94
- Args:
95
- proxy (Dict[str, str]): 代理配置
96
- """
97
- if proxy in self.proxies:
98
- self.proxies.remove(proxy)
99
- proxy_id = id(proxy)
100
- if proxy_id in self.proxy_status:
101
- del self.proxy_status[proxy_id]
102
-
103
-
104
- class CaptchaHandler:
105
- """验证码处理器类"""
106
-
107
- def __init__(self, captcha_service: Optional[Callable] = None):
108
- """
109
- 初始化验证码处理器
110
-
111
- Args:
112
- captcha_service (Optional[Callable]): 验证码识别服务
113
- """
114
- self.captcha_service = captcha_service
115
-
116
- async def recognize_captcha(self, image_data: bytes,
117
- captcha_type: str = "image") -> Optional[str]:
118
- """
119
- 识别验证码
120
-
121
- Args:
122
- image_data (bytes): 验证码图片数据
123
- captcha_type (str): 验证码类型
124
-
125
- Returns:
126
- Optional[str]: 识别结果
127
- """
128
- if self.captcha_service:
129
- try:
130
- return await self.captcha_service(image_data, captcha_type)
131
- except Exception:
132
- return None
133
- else:
134
- # 如果没有配置验证码服务,返回None
135
- return None
136
-
137
- async def handle_manual_captcha(self, prompt: str = "请输入验证码: ") -> str:
138
- """
139
- 处理手动验证码输入
140
-
141
- Args:
142
- prompt (str): 提示信息
143
-
144
- Returns:
145
- str: 用户输入的验证码
146
- """
147
- # 在实际应用中,这里可能需要与用户界面交互
148
- # 为了演示目的,我们模拟用户输入
149
- print(prompt)
150
- return input() if not asyncio.get_event_loop().is_running() else ""
151
-
152
-
153
- class AntiCrawler:
154
- """反爬虫应对工具类"""
155
-
156
- def __init__(self, proxies: Optional[List[Dict[str, str]]] = None,
157
- captcha_service: Optional[Callable] = None):
158
- """
159
- 初始化反爬虫应对工具
160
-
161
- Args:
162
- proxies (Optional[List[Dict[str, str]]]): 代理列表
163
- captcha_service (Optional[Callable]): 验证码识别服务
164
- """
165
- self.proxy_manager = ProxyPoolManager(proxies)
166
- self.captcha_handler = CaptchaHandler(captcha_service)
167
-
168
- def get_random_user_agent(self) -> str:
169
- """
170
- 获取随机User-Agent
171
-
172
- Returns:
173
- str: 随机User-Agent
174
- """
175
- user_agents = [
176
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
177
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
178
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
179
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
180
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59",
181
- "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
182
- "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Mobile Safari/537.36"
183
- ]
184
- return random.choice(user_agents)
185
-
186
- def rotate_proxy(self) -> Dict[str, str]:
187
- """
188
- 轮换代理
189
-
190
- Returns:
191
- Dict[str, str]: 代理配置
192
- """
193
- return self.proxy_manager.get_best_proxy()
194
-
195
- def handle_captcha(self, response_text: str) -> bool:
196
- """
197
- 检测是否遇到验证码
198
-
199
- Args:
200
- response_text (str): 响应文本
201
-
202
- Returns:
203
- bool: 是否遇到验证码
204
- """
205
- captcha_keywords = ["captcha", "verify", "验证", "验证码", "human verification"]
206
- return any(keyword in response_text.lower() for keyword in captcha_keywords)
207
-
208
- def detect_rate_limiting(self, status_code: int, response_headers: Dict[str, Any]) -> bool:
209
- """
210
- 检测是否遇到频率限制
211
-
212
- Args:
213
- status_code (int): HTTP状态码
214
- response_headers (Dict[str, Any]): 响应头
215
-
216
- Returns:
217
- bool: 是否遇到频率限制
218
- """
219
- # 检查状态码
220
- if status_code in [429, 503]:
221
- return True
222
-
223
- # 检查响应头
224
- rate_limit_headers = ["x-ratelimit-remaining", "retry-after", "x-ratelimit-reset"]
225
- return any(header.lower() in [k.lower() for k in response_headers.keys()]
226
- for header in rate_limit_headers)
227
-
228
- def random_delay(self, min_delay: float = 1.0, max_delay: float = 3.0) -> None:
229
- """
230
- 随机延迟,避免请求过于频繁
231
-
232
- Args:
233
- min_delay (float): 最小延迟时间(秒)
234
- max_delay (float): 最大延迟时间(秒)
235
- """
236
- delay = random.uniform(min_delay, max_delay)
237
- time.sleep(delay)
238
-
239
- async def async_random_delay(self, min_delay: float = 1.0, max_delay: float = 3.0) -> None:
240
- """
241
- 异步随机延迟,避免请求过于频繁
242
-
243
- Args:
244
- min_delay (float): 最小延迟时间(秒)
245
- max_delay (float): 最大延迟时间(秒)
246
- """
247
- delay = random.uniform(min_delay, max_delay)
248
- await asyncio.sleep(delay)
249
-
250
-
251
- # 便捷函数
252
- def get_random_user_agent() -> str:
253
- """获取随机User-Agent"""
254
- return AntiCrawler().get_random_user_agent()
255
-
256
-
257
- def rotate_proxy(proxies: Optional[List[Dict[str, str]]] = None) -> Dict[str, str]:
258
- """轮换代理"""
259
- return AntiCrawler(proxies).rotate_proxy()
260
-
261
-
262
- def handle_captcha(response_text: str) -> bool:
263
- """检测是否遇到验证码"""
264
- return AntiCrawler().handle_captcha(response_text)
265
-
266
-
267
- def detect_rate_limiting(status_code: int, response_headers: Dict[str, Any]) -> bool:
268
- """检测是否遇到频率限制"""
269
- return AntiCrawler().detect_rate_limiting(status_code, response_headers)
@@ -1,26 +0,0 @@
1
- # -*- coding: UTF-8 -*-
2
- """
3
- 类加载器工具模块
4
- ==============
5
- 提供动态类加载功能,避免循环依赖问题。
6
- """
7
- import importlib
8
- from typing import Any
9
-
10
-
11
- def load_class(path: str) -> Any:
12
- """
13
- 动态加载类
14
-
15
- Args:
16
- path: 类的完整路径,如 'package.module.ClassName'
17
-
18
- Returns:
19
- 加载的类对象
20
- """
21
- try:
22
- module_path, class_name = path.rsplit('.', 1)
23
- module = importlib.import_module(module_path)
24
- return getattr(module, class_name)
25
- except (ValueError, ImportError, AttributeError) as e:
26
- raise ImportError(f"无法加载类 '{path}': {e}")
@@ -1,357 +0,0 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- """
4
- 误处理工具
5
- 提供更详细、更一致的错误处理和日志记录机制
6
- """
7
- import traceback
8
- from datetime import datetime
9
- from functools import wraps
10
- from typing import Optional, Callable, Any, Dict, List
11
-
12
- from crawlo.utils.log import get_logger
13
-
14
-
15
- class ErrorContext:
16
- """错误上下文信息"""
17
-
18
- def __init__(self, context: str = "", module: str = "", function: str = ""):
19
- self.context = context
20
- self.module = module
21
- self.function = function
22
- self.timestamp = datetime.now()
23
-
24
- def __str__(self):
25
- parts = []
26
- if self.module:
27
- parts.append(f"Module: {self.module}")
28
- if self.function:
29
- parts.append(f"Function: {self.function}")
30
- if self.context:
31
- parts.append(f"Context: {self.context}")
32
- parts.append(f"Time: {self.timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
33
- return " | ".join(parts)
34
-
35
-
36
- class DetailedException(Exception):
37
- """带有详细信息的异常基类"""
38
-
39
- def __init__(self, message: str, context: Optional[ErrorContext] = None,
40
- error_code: Optional[str] = None, **kwargs):
41
- super().__init__(message)
42
- self.context = context
43
- self.error_code = error_code
44
- self.details = kwargs
45
- self.timestamp = datetime.now()
46
-
47
- def __str__(self):
48
- base_msg = super().__str__()
49
- if self.context:
50
- return f"{base_msg} ({self.context})"
51
- return base_msg
52
-
53
- def get_full_details(self) -> Dict:
54
- """获取完整的错误详情"""
55
- return {
56
- "message": str(self),
57
- "error_code": self.error_code,
58
- "context": str(self.context) if self.context else None,
59
- "details": self.details,
60
- "timestamp": self.timestamp.isoformat(),
61
- "exception_type": self.__class__.__name__
62
- }
63
-
64
-
65
- class EnhancedErrorHandler:
66
- """增强版错误处理器"""
67
-
68
- def __init__(self, logger_name: str = __name__, log_level: str = 'ERROR'):
69
- self.logger = get_logger(logger_name, log_level)
70
- self.error_history: List[Dict] = [] # 错误历史记录
71
- self.max_history_size = 100 # 最大历史记录数
72
-
73
- def handle_error(self, exception: Exception, context: Optional[ErrorContext] = None,
74
- raise_error: bool = True, log_error: bool = True,
75
- extra_info: Optional[Dict] = None) -> Dict:
76
- """
77
- 增强版错误处理
78
-
79
- Args:
80
- exception: 异常对象
81
- context: 错误上下文信息
82
- raise_error: 是否重新抛出异常
83
- log_error: 是否记录错误日志
84
- extra_info: 额外的错误信息
85
-
86
- Returns:
87
- 包含错误详情的字典
88
- """
89
- # 构建错误详情
90
- error_details = {
91
- "exception": exception,
92
- "exception_type": type(exception).__name__,
93
- "message": str(exception),
94
- "context": str(context) if context else None,
95
- "timestamp": datetime.now().isoformat(),
96
- "traceback": traceback.format_exc() if log_error else None,
97
- "extra_info": extra_info or {}
98
- }
99
-
100
- # 记录到历史
101
- self._record_error(error_details)
102
-
103
- # 记录日志
104
- if log_error:
105
- self._log_error(error_details)
106
-
107
- # 重新抛出异常
108
- if raise_error:
109
- raise exception
110
-
111
- return error_details
112
-
113
- def _log_error(self, error_details: Dict):
114
- """记录错误日志"""
115
- # 基本错误信息
116
- context_info = error_details.get("context", "")
117
- message = error_details["message"]
118
- error_msg = f"{message} [{context_info}]" if context_info else message
119
-
120
- # 记录错误
121
- self.logger.error(error_msg)
122
-
123
- # 记录详细信息
124
- if error_details.get("traceback"):
125
- self.logger.debug(f"详细错误信息:\n{error_details['traceback']}")
126
-
127
- # 记录额外信息
128
- if error_details.get("extra_info"):
129
- self.logger.debug(f"额外信息: {error_details['extra_info']}")
130
-
131
- def _record_error(self, error_details: Dict):
132
- """记录错误到历史"""
133
- self.error_history.append(error_details)
134
- # 限制历史记录大小
135
- if len(self.error_history) > self.max_history_size:
136
- self.error_history.pop(0)
137
-
138
- def safe_call(self, func: Callable, *args, default_return=None,
139
- context: Optional[ErrorContext] = None, **kwargs) -> Any:
140
- """
141
- 安全调用函数,捕获并处理异常
142
-
143
- Args:
144
- func: 要调用的函数
145
- *args: 函数参数
146
- default_return: 默认返回值
147
- context: 错误上下文
148
- **kwargs: 函数关键字参数
149
-
150
- Returns:
151
- 函数返回值或默认值
152
- """
153
- try:
154
- return func(*args, **kwargs)
155
- except Exception as e:
156
- self.handle_error(e, context=context, raise_error=False)
157
- return default_return
158
-
159
- def retry_on_failure(self, max_retries: int = 3, delay: float = 1.0,
160
- exceptions: tuple = (Exception,), backoff_factor: float = 1.0,
161
- context: Optional[ErrorContext] = None):
162
- """
163
- 装饰器:失败时重试(增强版)
164
-
165
- Args:
166
- max_retries: 最大重试次数
167
- delay: 初始重试间隔(秒)
168
- exceptions: 需要重试的异常类型
169
- backoff_factor: 退避因子(每次重试间隔乘以此因子)
170
- context: 错误上下文
171
- """
172
- def decorator(func):
173
- @wraps(func)
174
- async def async_wrapper(*args, **kwargs):
175
- last_exception = None
176
- current_delay = delay
177
-
178
- for attempt in range(max_retries + 1):
179
- try:
180
- return await func(*args, **kwargs)
181
- except exceptions as e:
182
- last_exception = e
183
- if attempt < max_retries:
184
- # 记录重试信息
185
- retry_context = ErrorContext(
186
- context=f"函数 {func.__name__} 执行失败 (尝试 {attempt + 1}/{max_retries + 1})",
187
- module=context.module if context else "",
188
- function=func.__name__
189
- ) if context else None
190
-
191
- self.logger.warning(
192
- f"函数 {func.__name__} 执行失败 (尝试 {attempt + 1}/{max_retries + 1}): {e}"
193
- )
194
-
195
- import asyncio
196
- await asyncio.sleep(current_delay)
197
- current_delay *= backoff_factor # 指数退避
198
- else:
199
- # 最后一次尝试失败
200
- final_context = ErrorContext(
201
- context=f"函数 {func.__name__} 执行失败,已达到最大重试次数",
202
- module=context.module if context else "",
203
- function=func.__name__
204
- ) if context else None
205
-
206
- self.logger.error(
207
- f"函数 {func.__name__} 执行失败,已达到最大重试次数: {e}"
208
- )
209
- raise last_exception
210
-
211
- @wraps(func)
212
- def sync_wrapper(*args, **kwargs):
213
- last_exception = None
214
- current_delay = delay
215
-
216
- for attempt in range(max_retries + 1):
217
- try:
218
- return func(*args, **kwargs)
219
- except exceptions as e:
220
- last_exception = e
221
- if attempt < max_retries:
222
- # 记录重试信息
223
- retry_context = ErrorContext(
224
- context=f"函数 {func.__name__} 执行失败 (尝试 {attempt + 1}/{max_retries + 1})",
225
- module=context.module if context else "",
226
- function=func.__name__
227
- ) if context else None
228
-
229
- self.logger.warning(
230
- f"函数 {func.__name__} 执行失败 (尝试 {attempt + 1}/{max_retries + 1}): {e}"
231
- )
232
-
233
- import time
234
- time.sleep(current_delay)
235
- current_delay *= backoff_factor # 指数退避
236
- else:
237
- # 最后一次尝试失败
238
- final_context = ErrorContext(
239
- context=f"函数 {func.__name__} 执行失败,已达到最大重试次数",
240
- module=context.module if context else "",
241
- function=func.__name__
242
- ) if context else None
243
-
244
- self.logger.error(
245
- f"函数 {func.__name__} 执行失败,已达到最大重试次数: {e}"
246
- )
247
- raise last_exception
248
-
249
- # 根据函数是否为异步函数返回相应的包装器
250
- import inspect
251
- if inspect.iscoroutinefunction(func):
252
- return async_wrapper
253
- else:
254
- return sync_wrapper
255
-
256
- return decorator
257
-
258
- def get_error_history(self) -> List[Dict]:
259
- """获取错误历史记录"""
260
- return self.error_history.copy()
261
-
262
- def clear_error_history(self):
263
- """清空错误历史记录"""
264
- self.error_history.clear()
265
-
266
-
267
- # 全局增强错误处理器实例
268
- enhanced_error_handler = EnhancedErrorHandler()
269
-
270
-
271
- def handle_exception(context: str = "", module: str = "", function: str = "",
272
- raise_error: bool = True, log_error: bool = True,
273
- error_code: Optional[str] = None):
274
- """
275
- 装饰器:处理函数异常(增强版)
276
-
277
- Args:
278
- context: 错误上下文描述
279
- module: 模块名称
280
- function: 函数名称
281
- raise_error: 是否重新抛出异常
282
- log_error: 是否记录错误日志
283
- error_code: 错误代码
284
- """
285
- def decorator(func):
286
- @wraps(func)
287
- async def async_wrapper(*args, **kwargs):
288
- try:
289
- return await func(*args, **kwargs)
290
- except Exception as e:
291
- error_context = ErrorContext(
292
- context=f"{context} - {func.__name__}",
293
- module=module,
294
- function=func.__name__
295
- )
296
-
297
- # 如果是详细异常,保留原有信息
298
- if isinstance(e, DetailedException):
299
- # 确保上下文信息完整
300
- if not e.context:
301
- e.context = error_context
302
- enhanced_error_handler.handle_error(
303
- e, context=e.context,
304
- raise_error=raise_error, log_error=log_error
305
- )
306
- else:
307
- # 包装为详细异常
308
- detailed_e = DetailedException(
309
- str(e), context=error_context, error_code=error_code
310
- )
311
- enhanced_error_handler.handle_error(
312
- detailed_e, context=error_context,
313
- raise_error=raise_error, log_error=log_error
314
- )
315
- if not raise_error:
316
- return None
317
-
318
- @wraps(func)
319
- def sync_wrapper(*args, **kwargs):
320
- try:
321
- return func(*args, **kwargs)
322
- except Exception as e:
323
- error_context = ErrorContext(
324
- context=f"{context} - {func.__name__}",
325
- module=module,
326
- function=func.__name__
327
- )
328
-
329
- # 如果是详细异常,保留原有信息
330
- if isinstance(e, DetailedException):
331
- # 确保上下文信息完整
332
- if not e.context:
333
- e.context = error_context
334
- enhanced_error_handler.handle_error(
335
- e, context=e.context,
336
- raise_error=raise_error, log_error=log_error
337
- )
338
- else:
339
- # 包装为详细异常
340
- detailed_e = DetailedException(
341
- str(e), context=error_context, error_code=error_code
342
- )
343
- enhanced_error_handler.handle_error(
344
- detailed_e, context=error_context,
345
- raise_error=raise_error, log_error=log_error
346
- )
347
- if not raise_error:
348
- return None
349
-
350
- # 根据函数是否为异步函数返回相应的包装器
351
- import inspect
352
- if inspect.iscoroutinefunction(func):
353
- return async_wrapper
354
- else:
355
- return sync_wrapper
356
-
357
- return decorator