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

Files changed (191) hide show
  1. crawlo/__init__.py +61 -61
  2. crawlo/__version__.py +1 -1
  3. crawlo/cleaners/__init__.py +60 -60
  4. crawlo/cleaners/data_formatter.py +225 -225
  5. crawlo/cleaners/encoding_converter.py +125 -125
  6. crawlo/cleaners/text_cleaner.py +232 -232
  7. crawlo/cli.py +65 -65
  8. crawlo/commands/__init__.py +14 -14
  9. crawlo/commands/check.py +594 -594
  10. crawlo/commands/genspider.py +151 -151
  11. crawlo/commands/help.py +132 -132
  12. crawlo/commands/list.py +155 -155
  13. crawlo/commands/run.py +292 -292
  14. crawlo/commands/startproject.py +418 -418
  15. crawlo/commands/stats.py +188 -188
  16. crawlo/commands/utils.py +186 -186
  17. crawlo/config.py +312 -312
  18. crawlo/config_validator.py +252 -252
  19. crawlo/core/__init__.py +2 -2
  20. crawlo/core/engine.py +354 -345
  21. crawlo/core/processor.py +40 -40
  22. crawlo/core/scheduler.py +143 -136
  23. crawlo/crawler.py +1027 -1027
  24. crawlo/downloader/__init__.py +266 -266
  25. crawlo/downloader/aiohttp_downloader.py +220 -220
  26. crawlo/downloader/cffi_downloader.py +256 -256
  27. crawlo/downloader/httpx_downloader.py +259 -259
  28. crawlo/downloader/hybrid_downloader.py +213 -213
  29. crawlo/downloader/playwright_downloader.py +402 -402
  30. crawlo/downloader/selenium_downloader.py +472 -472
  31. crawlo/event.py +11 -11
  32. crawlo/exceptions.py +81 -81
  33. crawlo/extension/__init__.py +37 -37
  34. crawlo/extension/health_check.py +141 -141
  35. crawlo/extension/log_interval.py +57 -57
  36. crawlo/extension/log_stats.py +81 -81
  37. crawlo/extension/logging_extension.py +43 -43
  38. crawlo/extension/memory_monitor.py +104 -104
  39. crawlo/extension/performance_profiler.py +133 -133
  40. crawlo/extension/request_recorder.py +107 -107
  41. crawlo/filters/__init__.py +154 -154
  42. crawlo/filters/aioredis_filter.py +280 -280
  43. crawlo/filters/memory_filter.py +269 -269
  44. crawlo/items/__init__.py +23 -23
  45. crawlo/items/base.py +21 -21
  46. crawlo/items/fields.py +53 -53
  47. crawlo/items/items.py +104 -104
  48. crawlo/middleware/__init__.py +21 -21
  49. crawlo/middleware/default_header.py +32 -32
  50. crawlo/middleware/download_delay.py +28 -28
  51. crawlo/middleware/middleware_manager.py +135 -135
  52. crawlo/middleware/proxy.py +272 -272
  53. crawlo/middleware/request_ignore.py +30 -30
  54. crawlo/middleware/response_code.py +18 -18
  55. crawlo/middleware/response_filter.py +26 -26
  56. crawlo/middleware/retry.py +124 -124
  57. crawlo/mode_manager.py +211 -211
  58. crawlo/network/__init__.py +21 -21
  59. crawlo/network/request.py +338 -338
  60. crawlo/network/response.py +359 -359
  61. crawlo/pipelines/__init__.py +21 -21
  62. crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
  63. crawlo/pipelines/console_pipeline.py +39 -39
  64. crawlo/pipelines/csv_pipeline.py +316 -316
  65. crawlo/pipelines/database_dedup_pipeline.py +224 -224
  66. crawlo/pipelines/json_pipeline.py +218 -218
  67. crawlo/pipelines/memory_dedup_pipeline.py +115 -115
  68. crawlo/pipelines/mongo_pipeline.py +131 -131
  69. crawlo/pipelines/mysql_pipeline.py +316 -316
  70. crawlo/pipelines/pipeline_manager.py +61 -61
  71. crawlo/pipelines/redis_dedup_pipeline.py +167 -167
  72. crawlo/project.py +187 -187
  73. crawlo/queue/pqueue.py +37 -37
  74. crawlo/queue/queue_manager.py +337 -334
  75. crawlo/queue/redis_priority_queue.py +298 -298
  76. crawlo/settings/__init__.py +7 -7
  77. crawlo/settings/default_settings.py +219 -219
  78. crawlo/settings/setting_manager.py +122 -122
  79. crawlo/spider/__init__.py +639 -639
  80. crawlo/stats_collector.py +59 -59
  81. crawlo/subscriber.py +130 -130
  82. crawlo/task_manager.py +30 -30
  83. crawlo/templates/crawlo.cfg.tmpl +10 -10
  84. crawlo/templates/project/__init__.py.tmpl +3 -3
  85. crawlo/templates/project/items.py.tmpl +17 -17
  86. crawlo/templates/project/middlewares.py.tmpl +109 -109
  87. crawlo/templates/project/pipelines.py.tmpl +96 -96
  88. crawlo/templates/project/run.py.tmpl +45 -45
  89. crawlo/templates/project/settings.py.tmpl +326 -326
  90. crawlo/templates/project/settings_distributed.py.tmpl +119 -119
  91. crawlo/templates/project/settings_gentle.py.tmpl +94 -94
  92. crawlo/templates/project/settings_high_performance.py.tmpl +151 -151
  93. crawlo/templates/project/settings_simple.py.tmpl +68 -68
  94. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  95. crawlo/templates/spider/spider.py.tmpl +141 -141
  96. crawlo/tools/__init__.py +182 -182
  97. crawlo/tools/anti_crawler.py +268 -268
  98. crawlo/tools/authenticated_proxy.py +240 -240
  99. crawlo/tools/data_validator.py +180 -180
  100. crawlo/tools/date_tools.py +35 -35
  101. crawlo/tools/distributed_coordinator.py +386 -386
  102. crawlo/tools/retry_mechanism.py +220 -220
  103. crawlo/tools/scenario_adapter.py +262 -262
  104. crawlo/utils/__init__.py +35 -35
  105. crawlo/utils/batch_processor.py +260 -260
  106. crawlo/utils/controlled_spider_mixin.py +439 -439
  107. crawlo/utils/date_tools.py +290 -290
  108. crawlo/utils/db_helper.py +343 -343
  109. crawlo/utils/enhanced_error_handler.py +359 -359
  110. crawlo/utils/env_config.py +105 -105
  111. crawlo/utils/error_handler.py +125 -125
  112. crawlo/utils/func_tools.py +82 -82
  113. crawlo/utils/large_scale_config.py +286 -286
  114. crawlo/utils/large_scale_helper.py +343 -343
  115. crawlo/utils/log.py +128 -128
  116. crawlo/utils/performance_monitor.py +284 -284
  117. crawlo/utils/queue_helper.py +175 -175
  118. crawlo/utils/redis_connection_pool.py +334 -334
  119. crawlo/utils/redis_key_validator.py +199 -199
  120. crawlo/utils/request.py +267 -267
  121. crawlo/utils/request_serializer.py +219 -219
  122. crawlo/utils/spider_loader.py +62 -62
  123. crawlo/utils/system.py +11 -11
  124. crawlo/utils/tools.py +4 -4
  125. crawlo/utils/url.py +39 -39
  126. crawlo-1.2.0.dist-info/METADATA +697 -0
  127. crawlo-1.2.0.dist-info/RECORD +190 -0
  128. examples/__init__.py +7 -7
  129. tests/DOUBLE_CRAWLO_PREFIX_FIX_REPORT.md +81 -81
  130. tests/__init__.py +7 -7
  131. tests/advanced_tools_example.py +275 -275
  132. tests/authenticated_proxy_example.py +236 -236
  133. tests/cleaners_example.py +160 -160
  134. tests/config_validation_demo.py +102 -102
  135. tests/controlled_spider_example.py +205 -205
  136. tests/date_tools_example.py +180 -180
  137. tests/dynamic_loading_example.py +523 -523
  138. tests/dynamic_loading_test.py +104 -104
  139. tests/env_config_example.py +133 -133
  140. tests/error_handling_example.py +171 -171
  141. tests/redis_key_validation_demo.py +130 -130
  142. tests/response_improvements_example.py +144 -144
  143. tests/test_advanced_tools.py +148 -148
  144. tests/test_all_redis_key_configs.py +145 -145
  145. tests/test_authenticated_proxy.py +141 -141
  146. tests/test_cleaners.py +54 -54
  147. tests/test_comprehensive.py +146 -146
  148. tests/test_config_validator.py +193 -193
  149. tests/test_date_tools.py +123 -123
  150. tests/test_double_crawlo_fix.py +207 -207
  151. tests/test_double_crawlo_fix_simple.py +124 -124
  152. tests/test_dynamic_downloaders_proxy.py +124 -124
  153. tests/test_dynamic_proxy.py +92 -92
  154. tests/test_dynamic_proxy_config.py +146 -146
  155. tests/test_dynamic_proxy_real.py +109 -109
  156. tests/test_edge_cases.py +303 -303
  157. tests/test_enhanced_error_handler.py +270 -270
  158. tests/test_env_config.py +121 -121
  159. tests/test_error_handler_compatibility.py +112 -112
  160. tests/test_final_validation.py +153 -153
  161. tests/test_framework_env_usage.py +103 -103
  162. tests/test_integration.py +356 -356
  163. tests/test_item_dedup_redis_key.py +122 -122
  164. tests/test_parsel.py +29 -29
  165. tests/test_performance.py +327 -327
  166. tests/test_proxy_health_check.py +32 -32
  167. tests/test_proxy_middleware_integration.py +136 -136
  168. tests/test_proxy_providers.py +56 -56
  169. tests/test_proxy_stats.py +19 -19
  170. tests/test_proxy_strategies.py +59 -59
  171. tests/test_queue_manager_double_crawlo.py +174 -231
  172. tests/test_queue_manager_redis_key.py +176 -176
  173. tests/test_redis_config.py +28 -28
  174. tests/test_redis_connection_pool.py +294 -294
  175. tests/test_redis_key_naming.py +181 -181
  176. tests/test_redis_key_validator.py +123 -123
  177. tests/test_redis_queue.py +224 -224
  178. tests/test_request_serialization.py +70 -70
  179. tests/test_response_improvements.py +152 -152
  180. tests/test_scheduler.py +241 -241
  181. tests/test_simple_response.py +61 -61
  182. tests/test_telecom_spider_redis_key.py +205 -205
  183. tests/test_template_content.py +87 -87
  184. tests/test_template_redis_key.py +134 -134
  185. tests/test_tools.py +153 -153
  186. tests/tools_example.py +257 -257
  187. crawlo-1.1.8.dist-info/METADATA +0 -626
  188. crawlo-1.1.8.dist-info/RECORD +0 -190
  189. {crawlo-1.1.8.dist-info → crawlo-1.2.0.dist-info}/WHEEL +0 -0
  190. {crawlo-1.1.8.dist-info → crawlo-1.2.0.dist-info}/entry_points.txt +0 -0
  191. {crawlo-1.1.8.dist-info → crawlo-1.2.0.dist-info}/top_level.txt +0 -0
crawlo/network/request.py CHANGED
@@ -1,339 +1,339 @@
1
- #!/usr/bin/python
2
- # -*- coding: UTF-8 -*-
3
- """
4
- HTTP Request 封装模块
5
- ====================
6
- 提供功能完善的HTTP请求封装,支持:
7
- - JSON/表单数据自动处理
8
- - 优先级排序机制
9
- - 安全的深拷贝操作
10
- - 灵活的请求配置
11
- """
12
- import json
13
- from copy import deepcopy
14
- from urllib.parse import urlencode
15
- from w3lib.url import safe_url_string
16
- from typing import Dict, Optional, Callable, Union, Any, TypeVar, List
17
-
18
- from crawlo.utils.url import escape_ajax
19
-
20
-
21
- _Request = TypeVar("_Request", bound="Request")
22
-
23
-
24
- class RequestPriority:
25
- """请求优先级常量和工具类"""
26
- URGENT = -200 # 紧急任务
27
- HIGH = -100 # 高优先级
28
- NORMAL = 0 # 正常优先级(默认)
29
- LOW = 100 # 低优先级
30
- BACKGROUND = 200 # 后台任务
31
-
32
- @classmethod
33
- def get_all_priorities(cls) -> Dict[str, int]:
34
- """获取所有优先级常量"""
35
- return {
36
- 'URGENT': cls.URGENT,
37
- 'HIGH': cls.HIGH,
38
- 'NORMAL': cls.NORMAL,
39
- 'LOW': cls.LOW,
40
- 'BACKGROUND': cls.BACKGROUND
41
- }
42
-
43
- @classmethod
44
- def from_string(cls, priority_str: str) -> int:
45
- """从字符串获取优先级值"""
46
- priorities = cls.get_all_priorities()
47
- if priority_str.upper() not in priorities:
48
- raise ValueError(f"不支持的优先级: {priority_str}, 支持: {list(priorities.keys())}")
49
- return priorities[priority_str.upper()]
50
-
51
-
52
- class Request:
53
- """
54
- 封装一个 HTTP 请求对象,用于爬虫框架中表示一个待抓取的请求任务。
55
- 支持 JSON、表单、原始 body 提交,自动处理 Content-Type 与编码。
56
- 不支持文件上传(multipart/form-data),保持轻量。
57
- """
58
-
59
- __slots__ = (
60
- '_url',
61
- '_meta',
62
- 'callback',
63
- 'cb_kwargs',
64
- 'err_back',
65
- 'headers',
66
- 'body',
67
- 'method',
68
- 'cookies',
69
- 'priority',
70
- 'encoding',
71
- 'dont_filter',
72
- 'timeout',
73
- 'proxy',
74
- 'allow_redirects',
75
- 'auth',
76
- 'verify',
77
- 'flags',
78
- '_json_body',
79
- '_form_data',
80
- 'use_dynamic_loader',
81
- 'dynamic_loader_options'
82
- )
83
-
84
- def __init__(
85
- self,
86
- url: str,
87
- callback: Optional[Callable] = None,
88
- method: Optional[str] = 'GET',
89
- headers: Optional[Dict[str, str]] = None,
90
- body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
91
- form_data: Optional[Dict[Any, Any]] = None,
92
- json_body: Optional[Dict[Any, Any]] = None,
93
- cb_kwargs: Optional[Dict[str, Any]] = None,
94
- cookies: Optional[Dict[str, str]] = None,
95
- meta: Optional[Dict[str, Any]] = None,
96
- priority: int = RequestPriority.NORMAL,
97
- dont_filter: bool = False,
98
- timeout: Optional[float] = None,
99
- proxy: Optional[str] = None,
100
- allow_redirects: bool = True,
101
- auth: Optional[tuple] = None,
102
- verify: bool = True,
103
- flags: Optional[List[str]] = None,
104
- encoding: str = 'utf-8',
105
- # 动态加载相关参数
106
- use_dynamic_loader: bool = False,
107
- dynamic_loader_options: Optional[Dict[str, Any]] = None
108
- ):
109
- """
110
- 初始化请求对象。
111
-
112
- :param url: 请求 URL(必须)
113
- :param callback: 成功回调函数
114
- :param method: HTTP 方法,默认 GET
115
- :param headers: 请求头
116
- :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
117
- :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
118
- :param json_body: JSON 数据,自动序列化并设置 Content-Type
119
- :param cb_kwargs: 传递给 callback 的额外参数
120
- :param cookies: Cookies 字典
121
- :param meta: 元数据(跨中间件传递数据)
122
- :param priority: 优先级(数值越小越优先)
123
- :param dont_filter: 是否跳过去重
124
- :param timeout: 超时时间(秒)
125
- :param proxy: 代理地址,如 http://127.0.0.1:8080
126
- :param allow_redirects: 是否允许重定向
127
- :param auth: 认证元组 (username, password)
128
- :param verify: 是否验证 SSL 证书
129
- :param flags: 标记(用于调试或分类)
130
- :param encoding: 字符编码,默认 utf-8
131
- """
132
- self.callback = callback
133
- self.method = str(method).upper()
134
- self.headers = headers or {}
135
- self.cookies = cookies or {}
136
- self.priority = -priority # 用于排序:值越小优先级越高
137
-
138
- # 🔧 安全处理 meta,移除 logger 后再 deepcopy
139
- self._meta = self._safe_deepcopy_meta(meta) if meta is not None else {}
140
-
141
- self.timeout = self._meta.get('download_timeout', timeout)
142
- self.proxy = proxy
143
- self.allow_redirects = allow_redirects
144
- self.auth = auth
145
- self.verify = verify
146
- self.flags = flags or []
147
- self.encoding = encoding
148
- self.cb_kwargs = cb_kwargs or {}
149
- self.body = body
150
- # 保存高层语义参数(用于 copy)
151
- self._json_body = json_body
152
- self._form_data = form_data
153
-
154
- # 动态加载相关属性
155
- self.use_dynamic_loader = use_dynamic_loader
156
- self.dynamic_loader_options = dynamic_loader_options or {}
157
-
158
- # 构建 body
159
- if json_body is not None:
160
- if 'Content-Type' not in self.headers:
161
- self.headers['Content-Type'] = 'application/json'
162
- self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
163
- if self.method == 'GET':
164
- self.method = 'POST'
165
-
166
- elif form_data is not None:
167
- if self.method == 'GET':
168
- self.method = 'POST'
169
- if 'Content-Type' not in self.headers:
170
- self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
171
- query_str = urlencode(form_data)
172
- self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
173
-
174
-
175
- else:
176
- # 处理原始 body
177
- if isinstance(self.body, dict):
178
- if 'Content-Type' not in self.headers:
179
- self.headers['Content-Type'] = 'application/json'
180
- self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
181
- elif isinstance(self.body, str):
182
- self.body = self.body.encode(encoding)
183
-
184
- self.dont_filter = dont_filter
185
- self._set_url(url)
186
-
187
- @staticmethod
188
- def _safe_deepcopy_meta(meta: Dict[str, Any]) -> Dict[str, Any]:
189
- """安全地 deepcopy meta,移除 logger 后再复制"""
190
- import logging
191
-
192
- def clean_logger_recursive(obj):
193
- """递归移除 logger 对象"""
194
- if isinstance(obj, logging.Logger):
195
- return None
196
- elif isinstance(obj, dict):
197
- cleaned = {}
198
- for k, v in obj.items():
199
- if not (k == 'logger' or isinstance(v, logging.Logger)):
200
- cleaned[k] = clean_logger_recursive(v)
201
- return cleaned
202
- elif isinstance(obj, (list, tuple)):
203
- cleaned_list = []
204
- for item in obj:
205
- cleaned_item = clean_logger_recursive(item)
206
- if cleaned_item is not None:
207
- cleaned_list.append(cleaned_item)
208
- return type(obj)(cleaned_list)
209
- else:
210
- return obj
211
-
212
- # 先清理 logger,再 deepcopy
213
- cleaned_meta = clean_logger_recursive(meta)
214
- return deepcopy(cleaned_meta)
215
-
216
- def copy(self: _Request) -> _Request:
217
- """
218
- 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
219
- """
220
- return type(self)(
221
- url=self.url,
222
- callback=self.callback,
223
- method=self.method,
224
- headers=self.headers.copy(),
225
- body=None, # 由 form_data/json_body 重新生成
226
- form_data=self._form_data,
227
- json_body=self._json_body,
228
- cb_kwargs=deepcopy(self.cb_kwargs),
229
- err_back=self.err_back,
230
- cookies=self.cookies.copy(),
231
- meta=deepcopy(self._meta),
232
- priority=-self.priority,
233
- dont_filter=self.dont_filter,
234
- timeout=self.timeout,
235
- proxy=self.proxy,
236
- allow_redirects=self.allow_redirects,
237
- auth=self.auth,
238
- verify=self.verify,
239
- flags=self.flags.copy(),
240
- encoding=self.encoding,
241
- use_dynamic_loader=self.use_dynamic_loader,
242
- dynamic_loader_options=deepcopy(self.dynamic_loader_options)
243
- )
244
-
245
- def set_meta(self, key: str, value: Any) -> 'Request':
246
- """设置 meta 中的某个键值,支持链式调用。"""
247
- self._meta[key] = value
248
- return self
249
-
250
- def add_header(self, key: str, value: str) -> 'Request':
251
- """添加请求头,支持链式调用。"""
252
- self.headers[key] = value
253
- return self
254
-
255
- def add_headers(self, headers: Dict[str, str]) -> 'Request':
256
- """批量添加请求头,支持链式调用。"""
257
- self.headers.update(headers)
258
- return self
259
-
260
- def set_proxy(self, proxy: str) -> 'Request':
261
- """设置代理,支持链式调用。"""
262
- self.proxy = proxy
263
- return self
264
-
265
- def set_timeout(self, timeout: float) -> 'Request':
266
- """设置超时时间,支持链式调用。"""
267
- self.timeout = timeout
268
- return self
269
-
270
- def add_flag(self, flag: str) -> 'Request':
271
- """添加标记,支持链式调用。"""
272
- if flag not in self.flags:
273
- self.flags.append(flag)
274
- return self
275
-
276
- def remove_flag(self, flag: str) -> 'Request':
277
- """移除标记,支持链式调用。"""
278
- if flag in self.flags:
279
- self.flags.remove(flag)
280
- return self
281
-
282
- def set_dynamic_loader(self, use_dynamic: bool = True, options: Optional[Dict[str, Any]] = None) -> 'Request':
283
- """设置使用动态加载器,支持链式调用。"""
284
- self.use_dynamic_loader = use_dynamic
285
- if options:
286
- self.dynamic_loader_options = options
287
- # 同时在meta中设置标记,供混合下载器使用
288
- self._meta['use_dynamic_loader'] = use_dynamic
289
- return self
290
-
291
- def set_protocol_loader(self) -> 'Request':
292
- """强制使用协议加载器,支持链式调用。"""
293
- self.use_dynamic_loader = False
294
- self._meta['use_dynamic_loader'] = False
295
- self._meta['use_protocol_loader'] = True
296
- return self
297
-
298
- def _set_url(self, url: str) -> None:
299
- """安全设置 URL,确保格式正确。"""
300
- if not isinstance(url, str):
301
- raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
302
-
303
- if not url.strip():
304
- raise ValueError("URL 不能为空")
305
-
306
- # 检查危险的 URL scheme
307
- dangerous_schemes = ['file://', 'ftp://', 'javascript:', 'data:']
308
- if any(url.lower().startswith(scheme) for scheme in dangerous_schemes):
309
- raise ValueError(f"URL scheme 不安全: {url[:20]}...")
310
-
311
- s = safe_url_string(url, self.encoding)
312
- escaped_url = escape_ajax(s)
313
-
314
- if not escaped_url.startswith(('http://', 'https://')):
315
- raise ValueError(f"URL 缺少 HTTP(S) scheme: {escaped_url[:50]}...")
316
-
317
- # 检查 URL 长度
318
- if len(escaped_url) > 8192: # 大多数服务器支持的最大 URL 长度
319
- raise ValueError(f"URL 过长 (超过 8192 字符): {len(escaped_url)} 字符")
320
-
321
- self._url = escaped_url
322
-
323
- @property
324
- def url(self) -> str:
325
- return self._url
326
-
327
- @property
328
- def meta(self) -> Dict[str, Any]:
329
- return self._meta
330
-
331
- def __str__(self) -> str:
332
- return f'<Request url={self.url} method={self.method}>'
333
-
334
- def __repr__(self) -> str:
335
- return str(self)
336
-
337
- def __lt__(self, other: _Request) -> bool:
338
- """用于按优先级排序"""
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ HTTP Request 封装模块
5
+ ====================
6
+ 提供功能完善的HTTP请求封装,支持:
7
+ - JSON/表单数据自动处理
8
+ - 优先级排序机制
9
+ - 安全的深拷贝操作
10
+ - 灵活的请求配置
11
+ """
12
+ import json
13
+ from copy import deepcopy
14
+ from urllib.parse import urlencode
15
+ from w3lib.url import safe_url_string
16
+ from typing import Dict, Optional, Callable, Union, Any, TypeVar, List
17
+
18
+ from crawlo.utils.url import escape_ajax
19
+
20
+
21
+ _Request = TypeVar("_Request", bound="Request")
22
+
23
+
24
+ class RequestPriority:
25
+ """请求优先级常量和工具类"""
26
+ URGENT = -200 # 紧急任务
27
+ HIGH = -100 # 高优先级
28
+ NORMAL = 0 # 正常优先级(默认)
29
+ LOW = 100 # 低优先级
30
+ BACKGROUND = 200 # 后台任务
31
+
32
+ @classmethod
33
+ def get_all_priorities(cls) -> Dict[str, int]:
34
+ """获取所有优先级常量"""
35
+ return {
36
+ 'URGENT': cls.URGENT,
37
+ 'HIGH': cls.HIGH,
38
+ 'NORMAL': cls.NORMAL,
39
+ 'LOW': cls.LOW,
40
+ 'BACKGROUND': cls.BACKGROUND
41
+ }
42
+
43
+ @classmethod
44
+ def from_string(cls, priority_str: str) -> int:
45
+ """从字符串获取优先级值"""
46
+ priorities = cls.get_all_priorities()
47
+ if priority_str.upper() not in priorities:
48
+ raise ValueError(f"不支持的优先级: {priority_str}, 支持: {list(priorities.keys())}")
49
+ return priorities[priority_str.upper()]
50
+
51
+
52
+ class Request:
53
+ """
54
+ 封装一个 HTTP 请求对象,用于爬虫框架中表示一个待抓取的请求任务。
55
+ 支持 JSON、表单、原始 body 提交,自动处理 Content-Type 与编码。
56
+ 不支持文件上传(multipart/form-data),保持轻量。
57
+ """
58
+
59
+ __slots__ = (
60
+ '_url',
61
+ '_meta',
62
+ 'callback',
63
+ 'cb_kwargs',
64
+ 'err_back',
65
+ 'headers',
66
+ 'body',
67
+ 'method',
68
+ 'cookies',
69
+ 'priority',
70
+ 'encoding',
71
+ 'dont_filter',
72
+ 'timeout',
73
+ 'proxy',
74
+ 'allow_redirects',
75
+ 'auth',
76
+ 'verify',
77
+ 'flags',
78
+ '_json_body',
79
+ '_form_data',
80
+ 'use_dynamic_loader',
81
+ 'dynamic_loader_options'
82
+ )
83
+
84
+ def __init__(
85
+ self,
86
+ url: str,
87
+ callback: Optional[Callable] = None,
88
+ method: Optional[str] = 'GET',
89
+ headers: Optional[Dict[str, str]] = None,
90
+ body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
91
+ form_data: Optional[Dict[Any, Any]] = None,
92
+ json_body: Optional[Dict[Any, Any]] = None,
93
+ cb_kwargs: Optional[Dict[str, Any]] = None,
94
+ cookies: Optional[Dict[str, str]] = None,
95
+ meta: Optional[Dict[str, Any]] = None,
96
+ priority: int = RequestPriority.NORMAL,
97
+ dont_filter: bool = False,
98
+ timeout: Optional[float] = None,
99
+ proxy: Optional[str] = None,
100
+ allow_redirects: bool = True,
101
+ auth: Optional[tuple] = None,
102
+ verify: bool = True,
103
+ flags: Optional[List[str]] = None,
104
+ encoding: str = 'utf-8',
105
+ # 动态加载相关参数
106
+ use_dynamic_loader: bool = False,
107
+ dynamic_loader_options: Optional[Dict[str, Any]] = None
108
+ ):
109
+ """
110
+ 初始化请求对象。
111
+
112
+ :param url: 请求 URL(必须)
113
+ :param callback: 成功回调函数
114
+ :param method: HTTP 方法,默认 GET
115
+ :param headers: 请求头
116
+ :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
117
+ :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
118
+ :param json_body: JSON 数据,自动序列化并设置 Content-Type
119
+ :param cb_kwargs: 传递给 callback 的额外参数
120
+ :param cookies: Cookies 字典
121
+ :param meta: 元数据(跨中间件传递数据)
122
+ :param priority: 优先级(数值越小越优先)
123
+ :param dont_filter: 是否跳过去重
124
+ :param timeout: 超时时间(秒)
125
+ :param proxy: 代理地址,如 http://127.0.0.1:8080
126
+ :param allow_redirects: 是否允许重定向
127
+ :param auth: 认证元组 (username, password)
128
+ :param verify: 是否验证 SSL 证书
129
+ :param flags: 标记(用于调试或分类)
130
+ :param encoding: 字符编码,默认 utf-8
131
+ """
132
+ self.callback = callback
133
+ self.method = str(method).upper()
134
+ self.headers = headers or {}
135
+ self.cookies = cookies or {}
136
+ self.priority = -priority # 用于排序:值越小优先级越高
137
+
138
+ # 🔧 安全处理 meta,移除 logger 后再 deepcopy
139
+ self._meta = self._safe_deepcopy_meta(meta) if meta is not None else {}
140
+
141
+ self.timeout = self._meta.get('download_timeout', timeout)
142
+ self.proxy = proxy
143
+ self.allow_redirects = allow_redirects
144
+ self.auth = auth
145
+ self.verify = verify
146
+ self.flags = flags or []
147
+ self.encoding = encoding
148
+ self.cb_kwargs = cb_kwargs or {}
149
+ self.body = body
150
+ # 保存高层语义参数(用于 copy)
151
+ self._json_body = json_body
152
+ self._form_data = form_data
153
+
154
+ # 动态加载相关属性
155
+ self.use_dynamic_loader = use_dynamic_loader
156
+ self.dynamic_loader_options = dynamic_loader_options or {}
157
+
158
+ # 构建 body
159
+ if json_body is not None:
160
+ if 'Content-Type' not in self.headers:
161
+ self.headers['Content-Type'] = 'application/json'
162
+ self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
163
+ if self.method == 'GET':
164
+ self.method = 'POST'
165
+
166
+ elif form_data is not None:
167
+ if self.method == 'GET':
168
+ self.method = 'POST'
169
+ if 'Content-Type' not in self.headers:
170
+ self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
171
+ query_str = urlencode(form_data)
172
+ self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
173
+
174
+
175
+ else:
176
+ # 处理原始 body
177
+ if isinstance(self.body, dict):
178
+ if 'Content-Type' not in self.headers:
179
+ self.headers['Content-Type'] = 'application/json'
180
+ self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
181
+ elif isinstance(self.body, str):
182
+ self.body = self.body.encode(encoding)
183
+
184
+ self.dont_filter = dont_filter
185
+ self._set_url(url)
186
+
187
+ @staticmethod
188
+ def _safe_deepcopy_meta(meta: Dict[str, Any]) -> Dict[str, Any]:
189
+ """安全地 deepcopy meta,移除 logger 后再复制"""
190
+ import logging
191
+
192
+ def clean_logger_recursive(obj):
193
+ """递归移除 logger 对象"""
194
+ if isinstance(obj, logging.Logger):
195
+ return None
196
+ elif isinstance(obj, dict):
197
+ cleaned = {}
198
+ for k, v in obj.items():
199
+ if not (k == 'logger' or isinstance(v, logging.Logger)):
200
+ cleaned[k] = clean_logger_recursive(v)
201
+ return cleaned
202
+ elif isinstance(obj, (list, tuple)):
203
+ cleaned_list = []
204
+ for item in obj:
205
+ cleaned_item = clean_logger_recursive(item)
206
+ if cleaned_item is not None:
207
+ cleaned_list.append(cleaned_item)
208
+ return type(obj)(cleaned_list)
209
+ else:
210
+ return obj
211
+
212
+ # 先清理 logger,再 deepcopy
213
+ cleaned_meta = clean_logger_recursive(meta)
214
+ return deepcopy(cleaned_meta)
215
+
216
+ def copy(self: _Request) -> _Request:
217
+ """
218
+ 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
219
+ """
220
+ return type(self)(
221
+ url=self.url,
222
+ callback=self.callback,
223
+ method=self.method,
224
+ headers=self.headers.copy(),
225
+ body=None, # 由 form_data/json_body 重新生成
226
+ form_data=self._form_data,
227
+ json_body=self._json_body,
228
+ cb_kwargs=deepcopy(self.cb_kwargs),
229
+ err_back=self.err_back,
230
+ cookies=self.cookies.copy(),
231
+ meta=deepcopy(self._meta),
232
+ priority=-self.priority,
233
+ dont_filter=self.dont_filter,
234
+ timeout=self.timeout,
235
+ proxy=self.proxy,
236
+ allow_redirects=self.allow_redirects,
237
+ auth=self.auth,
238
+ verify=self.verify,
239
+ flags=self.flags.copy(),
240
+ encoding=self.encoding,
241
+ use_dynamic_loader=self.use_dynamic_loader,
242
+ dynamic_loader_options=deepcopy(self.dynamic_loader_options)
243
+ )
244
+
245
+ def set_meta(self, key: str, value: Any) -> 'Request':
246
+ """设置 meta 中的某个键值,支持链式调用。"""
247
+ self._meta[key] = value
248
+ return self
249
+
250
+ def add_header(self, key: str, value: str) -> 'Request':
251
+ """添加请求头,支持链式调用。"""
252
+ self.headers[key] = value
253
+ return self
254
+
255
+ def add_headers(self, headers: Dict[str, str]) -> 'Request':
256
+ """批量添加请求头,支持链式调用。"""
257
+ self.headers.update(headers)
258
+ return self
259
+
260
+ def set_proxy(self, proxy: str) -> 'Request':
261
+ """设置代理,支持链式调用。"""
262
+ self.proxy = proxy
263
+ return self
264
+
265
+ def set_timeout(self, timeout: float) -> 'Request':
266
+ """设置超时时间,支持链式调用。"""
267
+ self.timeout = timeout
268
+ return self
269
+
270
+ def add_flag(self, flag: str) -> 'Request':
271
+ """添加标记,支持链式调用。"""
272
+ if flag not in self.flags:
273
+ self.flags.append(flag)
274
+ return self
275
+
276
+ def remove_flag(self, flag: str) -> 'Request':
277
+ """移除标记,支持链式调用。"""
278
+ if flag in self.flags:
279
+ self.flags.remove(flag)
280
+ return self
281
+
282
+ def set_dynamic_loader(self, use_dynamic: bool = True, options: Optional[Dict[str, Any]] = None) -> 'Request':
283
+ """设置使用动态加载器,支持链式调用。"""
284
+ self.use_dynamic_loader = use_dynamic
285
+ if options:
286
+ self.dynamic_loader_options = options
287
+ # 同时在meta中设置标记,供混合下载器使用
288
+ self._meta['use_dynamic_loader'] = use_dynamic
289
+ return self
290
+
291
+ def set_protocol_loader(self) -> 'Request':
292
+ """强制使用协议加载器,支持链式调用。"""
293
+ self.use_dynamic_loader = False
294
+ self._meta['use_dynamic_loader'] = False
295
+ self._meta['use_protocol_loader'] = True
296
+ return self
297
+
298
+ def _set_url(self, url: str) -> None:
299
+ """安全设置 URL,确保格式正确。"""
300
+ if not isinstance(url, str):
301
+ raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
302
+
303
+ if not url.strip():
304
+ raise ValueError("URL 不能为空")
305
+
306
+ # 检查危险的 URL scheme
307
+ dangerous_schemes = ['file://', 'ftp://', 'javascript:', 'data:']
308
+ if any(url.lower().startswith(scheme) for scheme in dangerous_schemes):
309
+ raise ValueError(f"URL scheme 不安全: {url[:20]}...")
310
+
311
+ s = safe_url_string(url, self.encoding)
312
+ escaped_url = escape_ajax(s)
313
+
314
+ if not escaped_url.startswith(('http://', 'https://')):
315
+ raise ValueError(f"URL 缺少 HTTP(S) scheme: {escaped_url[:50]}...")
316
+
317
+ # 检查 URL 长度
318
+ if len(escaped_url) > 8192: # 大多数服务器支持的最大 URL 长度
319
+ raise ValueError(f"URL 过长 (超过 8192 字符): {len(escaped_url)} 字符")
320
+
321
+ self._url = escaped_url
322
+
323
+ @property
324
+ def url(self) -> str:
325
+ return self._url
326
+
327
+ @property
328
+ def meta(self) -> Dict[str, Any]:
329
+ return self._meta
330
+
331
+ def __str__(self) -> str:
332
+ return f'<Request url={self.url} method={self.method}>'
333
+
334
+ def __repr__(self) -> str:
335
+ return str(self)
336
+
337
+ def __lt__(self, other: _Request) -> bool:
338
+ """用于按优先级排序"""
339
339
  return self.priority < other.priority