crawlo 1.1.3__py3-none-any.whl → 1.1.4__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 (118) hide show
  1. crawlo/__init__.py +34 -34
  2. crawlo/__version__.py +1 -1
  3. crawlo/cli.py +40 -40
  4. crawlo/commands/__init__.py +13 -13
  5. crawlo/commands/check.py +594 -594
  6. crawlo/commands/genspider.py +151 -151
  7. crawlo/commands/list.py +155 -155
  8. crawlo/commands/run.py +285 -285
  9. crawlo/commands/startproject.py +196 -196
  10. crawlo/commands/stats.py +188 -188
  11. crawlo/commands/utils.py +186 -186
  12. crawlo/config.py +279 -279
  13. crawlo/core/__init__.py +2 -2
  14. crawlo/core/engine.py +171 -171
  15. crawlo/core/enhanced_engine.py +189 -189
  16. crawlo/core/processor.py +40 -40
  17. crawlo/core/scheduler.py +165 -165
  18. crawlo/crawler.py +1027 -1027
  19. crawlo/downloader/__init__.py +242 -242
  20. crawlo/downloader/aiohttp_downloader.py +212 -212
  21. crawlo/downloader/cffi_downloader.py +251 -251
  22. crawlo/downloader/httpx_downloader.py +259 -259
  23. crawlo/event.py +11 -11
  24. crawlo/exceptions.py +81 -81
  25. crawlo/extension/__init__.py +38 -31
  26. crawlo/extension/health_check.py +142 -0
  27. crawlo/extension/log_interval.py +58 -49
  28. crawlo/extension/log_stats.py +82 -44
  29. crawlo/extension/logging_extension.py +44 -35
  30. crawlo/extension/memory_monitor.py +89 -0
  31. crawlo/extension/performance_profiler.py +118 -0
  32. crawlo/extension/request_recorder.py +108 -0
  33. crawlo/filters/__init__.py +154 -154
  34. crawlo/filters/aioredis_filter.py +241 -241
  35. crawlo/filters/memory_filter.py +269 -269
  36. crawlo/items/__init__.py +23 -23
  37. crawlo/items/base.py +21 -21
  38. crawlo/items/fields.py +53 -53
  39. crawlo/items/items.py +104 -104
  40. crawlo/middleware/__init__.py +21 -21
  41. crawlo/middleware/default_header.py +32 -32
  42. crawlo/middleware/download_delay.py +28 -28
  43. crawlo/middleware/middleware_manager.py +135 -135
  44. crawlo/middleware/proxy.py +248 -248
  45. crawlo/middleware/request_ignore.py +30 -30
  46. crawlo/middleware/response_code.py +18 -18
  47. crawlo/middleware/response_filter.py +26 -26
  48. crawlo/middleware/retry.py +124 -124
  49. crawlo/mode_manager.py +200 -200
  50. crawlo/network/__init__.py +21 -21
  51. crawlo/network/request.py +311 -311
  52. crawlo/network/response.py +271 -271
  53. crawlo/pipelines/__init__.py +21 -21
  54. crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
  55. crawlo/pipelines/console_pipeline.py +39 -39
  56. crawlo/pipelines/csv_pipeline.py +316 -316
  57. crawlo/pipelines/database_dedup_pipeline.py +224 -224
  58. crawlo/pipelines/json_pipeline.py +218 -218
  59. crawlo/pipelines/memory_dedup_pipeline.py +115 -115
  60. crawlo/pipelines/mongo_pipeline.py +132 -117
  61. crawlo/pipelines/mysql_pipeline.py +317 -195
  62. crawlo/pipelines/pipeline_manager.py +56 -56
  63. crawlo/pipelines/redis_dedup_pipeline.py +162 -162
  64. crawlo/project.py +153 -153
  65. crawlo/queue/pqueue.py +37 -37
  66. crawlo/queue/queue_manager.py +307 -307
  67. crawlo/queue/redis_priority_queue.py +208 -208
  68. crawlo/settings/__init__.py +7 -7
  69. crawlo/settings/default_settings.py +278 -244
  70. crawlo/settings/setting_manager.py +99 -99
  71. crawlo/spider/__init__.py +639 -639
  72. crawlo/stats_collector.py +59 -59
  73. crawlo/subscriber.py +131 -106
  74. crawlo/task_manager.py +30 -30
  75. crawlo/templates/crawlo.cfg.tmpl +10 -10
  76. crawlo/templates/project/__init__.py.tmpl +3 -3
  77. crawlo/templates/project/items.py.tmpl +17 -17
  78. crawlo/templates/project/middlewares.py.tmpl +111 -87
  79. crawlo/templates/project/pipelines.py.tmpl +97 -341
  80. crawlo/templates/project/run.py.tmpl +251 -251
  81. crawlo/templates/project/settings.py.tmpl +279 -250
  82. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  83. crawlo/templates/spider/spider.py.tmpl +142 -178
  84. crawlo/utils/__init__.py +7 -7
  85. crawlo/utils/controlled_spider_mixin.py +439 -439
  86. crawlo/utils/date_tools.py +233 -233
  87. crawlo/utils/db_helper.py +343 -343
  88. crawlo/utils/func_tools.py +82 -82
  89. crawlo/utils/large_scale_config.py +286 -286
  90. crawlo/utils/large_scale_helper.py +343 -343
  91. crawlo/utils/log.py +128 -128
  92. crawlo/utils/queue_helper.py +175 -175
  93. crawlo/utils/request.py +267 -267
  94. crawlo/utils/request_serializer.py +219 -219
  95. crawlo/utils/spider_loader.py +62 -62
  96. crawlo/utils/system.py +11 -11
  97. crawlo/utils/tools.py +4 -4
  98. crawlo/utils/url.py +39 -39
  99. crawlo-1.1.4.dist-info/METADATA +403 -0
  100. crawlo-1.1.4.dist-info/RECORD +117 -0
  101. examples/__init__.py +7 -7
  102. examples/controlled_spider_example.py +205 -205
  103. tests/__init__.py +7 -7
  104. tests/test_final_validation.py +153 -153
  105. tests/test_proxy_health_check.py +32 -32
  106. tests/test_proxy_middleware_integration.py +136 -136
  107. tests/test_proxy_providers.py +56 -56
  108. tests/test_proxy_stats.py +19 -19
  109. tests/test_proxy_strategies.py +59 -59
  110. tests/test_redis_config.py +28 -28
  111. tests/test_redis_queue.py +224 -224
  112. tests/test_request_serialization.py +70 -70
  113. tests/test_scheduler.py +241 -241
  114. crawlo-1.1.3.dist-info/METADATA +0 -635
  115. crawlo-1.1.3.dist-info/RECORD +0 -113
  116. {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/WHEEL +0 -0
  117. {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/entry_points.txt +0 -0
  118. {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/top_level.txt +0 -0
@@ -1,21 +1,21 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- """
4
- Crawlo Network Module
5
- ====================
6
- 提供HTTP请求和响应对象的封装。
7
-
8
- 主要组件:
9
- - Request: HTTP请求封装
10
- - Response: HTTP响应封装
11
- - RequestPriority: 请求优先级常量
12
- """
13
-
14
- from .request import Request, RequestPriority
15
- from .response import Response
16
-
17
- __all__ = [
18
- 'Request',
19
- 'RequestPriority',
20
- 'Response',
21
- ]
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ """
4
+ Crawlo Network Module
5
+ ====================
6
+ 提供HTTP请求和响应对象的封装。
7
+
8
+ 主要组件:
9
+ - Request: HTTP请求封装
10
+ - Response: HTTP响应封装
11
+ - RequestPriority: 请求优先级常量
12
+ """
13
+
14
+ from .request import Request, RequestPriority
15
+ from .response import Response
16
+
17
+ __all__ = [
18
+ 'Request',
19
+ 'RequestPriority',
20
+ 'Response',
21
+ ]
crawlo/network/request.py CHANGED
@@ -1,312 +1,312 @@
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
- )
81
-
82
- def __init__(
83
- self,
84
- url: str,
85
- callback: Optional[Callable] = None,
86
- method: Optional[str] = 'GET',
87
- headers: Optional[Dict[str, str]] = None,
88
- body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
89
- form_data: Optional[Dict[Any, Any]] = None,
90
- json_body: Optional[Dict[Any, Any]] = None,
91
- cb_kwargs: Optional[Dict[str, Any]] = None,
92
- cookies: Optional[Dict[str, str]] = None,
93
- meta: Optional[Dict[str, Any]] = None,
94
- priority: int = RequestPriority.NORMAL,
95
- dont_filter: bool = False,
96
- timeout: Optional[float] = None,
97
- proxy: Optional[str] = None,
98
- allow_redirects: bool = True,
99
- auth: Optional[tuple] = None,
100
- verify: bool = True,
101
- flags: Optional[List[str]] = None,
102
- encoding: str = 'utf-8'
103
- ):
104
- """
105
- 初始化请求对象。
106
-
107
- :param url: 请求 URL(必须)
108
- :param callback: 成功回调函数
109
- :param method: HTTP 方法,默认 GET
110
- :param headers: 请求头
111
- :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
112
- :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
113
- :param json_body: JSON 数据,自动序列化并设置 Content-Type
114
- :param cb_kwargs: 传递给 callback 的额外参数
115
- :param cookies: Cookies 字典
116
- :param meta: 元数据(跨中间件传递数据)
117
- :param priority: 优先级(数值越小越优先)
118
- :param dont_filter: 是否跳过去重
119
- :param timeout: 超时时间(秒)
120
- :param proxy: 代理地址,如 http://127.0.0.1:8080
121
- :param allow_redirects: 是否允许重定向
122
- :param auth: 认证元组 (username, password)
123
- :param verify: 是否验证 SSL 证书
124
- :param flags: 标记(用于调试或分类)
125
- :param encoding: 字符编码,默认 utf-8
126
- """
127
- self.callback = callback
128
- self.method = str(method).upper()
129
- self.headers = headers or {}
130
- self.cookies = cookies or {}
131
- self.priority = -priority # 用于排序:值越小优先级越高
132
-
133
- # 🔧 安全处理 meta,移除 logger 后再 deepcopy
134
- self._meta = self._safe_deepcopy_meta(meta) if meta is not None else {}
135
-
136
- self.timeout = self._meta.get('download_timeout', timeout)
137
- self.proxy = proxy
138
- self.allow_redirects = allow_redirects
139
- self.auth = auth
140
- self.verify = verify
141
- self.flags = flags or []
142
- self.encoding = encoding
143
- self.cb_kwargs = cb_kwargs or {}
144
- self.body = body
145
- # 保存高层语义参数(用于 copy)
146
- self._json_body = json_body
147
- self._form_data = form_data
148
-
149
- # 构建 body
150
- if json_body is not None:
151
- if 'Content-Type' not in self.headers:
152
- self.headers['Content-Type'] = 'application/json'
153
- self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
154
- if self.method == 'GET':
155
- self.method = 'POST'
156
-
157
- elif form_data is not None:
158
- if self.method == 'GET':
159
- self.method = 'POST'
160
- if 'Content-Type' not in self.headers:
161
- self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
162
- query_str = urlencode(form_data)
163
- self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
164
-
165
-
166
- else:
167
- # 处理原始 body
168
- if isinstance(self.body, dict):
169
- if 'Content-Type' not in self.headers:
170
- self.headers['Content-Type'] = 'application/json'
171
- self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
172
- elif isinstance(self.body, str):
173
- self.body = self.body.encode(encoding)
174
-
175
- self.dont_filter = dont_filter
176
- self._set_url(url)
177
-
178
- @staticmethod
179
- def _safe_deepcopy_meta(meta: Dict[str, Any]) -> Dict[str, Any]:
180
- """安全地 deepcopy meta,移除 logger 后再复制"""
181
- import logging
182
-
183
- def clean_logger_recursive(obj):
184
- """递归移除 logger 对象"""
185
- if isinstance(obj, logging.Logger):
186
- return None
187
- elif isinstance(obj, dict):
188
- cleaned = {}
189
- for k, v in obj.items():
190
- if not (k == 'logger' or isinstance(v, logging.Logger)):
191
- cleaned[k] = clean_logger_recursive(v)
192
- return cleaned
193
- elif isinstance(obj, (list, tuple)):
194
- cleaned_list = []
195
- for item in obj:
196
- cleaned_item = clean_logger_recursive(item)
197
- if cleaned_item is not None:
198
- cleaned_list.append(cleaned_item)
199
- return type(obj)(cleaned_list)
200
- else:
201
- return obj
202
-
203
- # 先清理 logger,再 deepcopy
204
- cleaned_meta = clean_logger_recursive(meta)
205
- return deepcopy(cleaned_meta)
206
-
207
- def copy(self: _Request) -> _Request:
208
- """
209
- 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
210
- """
211
- return type(self)(
212
- url=self.url,
213
- callback=self.callback,
214
- method=self.method,
215
- headers=self.headers.copy(),
216
- body=None, # 由 form_data/json_body 重新生成
217
- form_data=self._form_data,
218
- json_body=self._json_body,
219
- cb_kwargs=deepcopy(self.cb_kwargs),
220
- err_back=self.err_back,
221
- cookies=self.cookies.copy(),
222
- meta=deepcopy(self._meta),
223
- priority=-self.priority,
224
- dont_filter=self.dont_filter,
225
- timeout=self.timeout,
226
- proxy=self.proxy,
227
- allow_redirects=self.allow_redirects,
228
- auth=self.auth,
229
- verify=self.verify,
230
- flags=self.flags.copy(),
231
- encoding=self.encoding
232
- )
233
-
234
- def set_meta(self, key: str, value: Any) -> 'Request':
235
- """设置 meta 中的某个键值,支持链式调用。"""
236
- self._meta[key] = value
237
- return self
238
-
239
- def add_header(self, key: str, value: str) -> 'Request':
240
- """添加请求头,支持链式调用。"""
241
- self.headers[key] = value
242
- return self
243
-
244
- def add_headers(self, headers: Dict[str, str]) -> 'Request':
245
- """批量添加请求头,支持链式调用。"""
246
- self.headers.update(headers)
247
- return self
248
-
249
- def set_proxy(self, proxy: str) -> 'Request':
250
- """设置代理,支持链式调用。"""
251
- self.proxy = proxy
252
- return self
253
-
254
- def set_timeout(self, timeout: float) -> 'Request':
255
- """设置超时时间,支持链式调用。"""
256
- self.timeout = timeout
257
- return self
258
-
259
- def add_flag(self, flag: str) -> 'Request':
260
- """添加标记,支持链式调用。"""
261
- if flag not in self.flags:
262
- self.flags.append(flag)
263
- return self
264
-
265
- def remove_flag(self, flag: str) -> 'Request':
266
- """移除标记,支持链式调用。"""
267
- if flag in self.flags:
268
- self.flags.remove(flag)
269
- return self
270
-
271
- def _set_url(self, url: str) -> None:
272
- """安全设置 URL,确保格式正确。"""
273
- if not isinstance(url, str):
274
- raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
275
-
276
- if not url.strip():
277
- raise ValueError("URL 不能为空")
278
-
279
- # 检查危险的 URL scheme
280
- dangerous_schemes = ['file://', 'ftp://', 'javascript:', 'data:']
281
- if any(url.lower().startswith(scheme) for scheme in dangerous_schemes):
282
- raise ValueError(f"URL scheme 不安全: {url[:20]}...")
283
-
284
- s = safe_url_string(url, self.encoding)
285
- escaped_url = escape_ajax(s)
286
-
287
- if not escaped_url.startswith(('http://', 'https://')):
288
- raise ValueError(f"URL 缺少 HTTP(S) scheme: {escaped_url[:50]}...")
289
-
290
- # 检查 URL 长度
291
- if len(escaped_url) > 8192: # 大多数服务器支持的最大 URL 长度
292
- raise ValueError(f"URL 过长 (超过 8192 字符): {len(escaped_url)} 字符")
293
-
294
- self._url = escaped_url
295
-
296
- @property
297
- def url(self) -> str:
298
- return self._url
299
-
300
- @property
301
- def meta(self) -> Dict[str, Any]:
302
- return self._meta
303
-
304
- def __str__(self) -> str:
305
- return f'<Request url={self.url} method={self.method}>'
306
-
307
- def __repr__(self) -> str:
308
- return str(self)
309
-
310
- def __lt__(self, other: _Request) -> bool:
311
- """用于按优先级排序"""
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
+ )
81
+
82
+ def __init__(
83
+ self,
84
+ url: str,
85
+ callback: Optional[Callable] = None,
86
+ method: Optional[str] = 'GET',
87
+ headers: Optional[Dict[str, str]] = None,
88
+ body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
89
+ form_data: Optional[Dict[Any, Any]] = None,
90
+ json_body: Optional[Dict[Any, Any]] = None,
91
+ cb_kwargs: Optional[Dict[str, Any]] = None,
92
+ cookies: Optional[Dict[str, str]] = None,
93
+ meta: Optional[Dict[str, Any]] = None,
94
+ priority: int = RequestPriority.NORMAL,
95
+ dont_filter: bool = False,
96
+ timeout: Optional[float] = None,
97
+ proxy: Optional[str] = None,
98
+ allow_redirects: bool = True,
99
+ auth: Optional[tuple] = None,
100
+ verify: bool = True,
101
+ flags: Optional[List[str]] = None,
102
+ encoding: str = 'utf-8'
103
+ ):
104
+ """
105
+ 初始化请求对象。
106
+
107
+ :param url: 请求 URL(必须)
108
+ :param callback: 成功回调函数
109
+ :param method: HTTP 方法,默认 GET
110
+ :param headers: 请求头
111
+ :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
112
+ :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
113
+ :param json_body: JSON 数据,自动序列化并设置 Content-Type
114
+ :param cb_kwargs: 传递给 callback 的额外参数
115
+ :param cookies: Cookies 字典
116
+ :param meta: 元数据(跨中间件传递数据)
117
+ :param priority: 优先级(数值越小越优先)
118
+ :param dont_filter: 是否跳过去重
119
+ :param timeout: 超时时间(秒)
120
+ :param proxy: 代理地址,如 http://127.0.0.1:8080
121
+ :param allow_redirects: 是否允许重定向
122
+ :param auth: 认证元组 (username, password)
123
+ :param verify: 是否验证 SSL 证书
124
+ :param flags: 标记(用于调试或分类)
125
+ :param encoding: 字符编码,默认 utf-8
126
+ """
127
+ self.callback = callback
128
+ self.method = str(method).upper()
129
+ self.headers = headers or {}
130
+ self.cookies = cookies or {}
131
+ self.priority = -priority # 用于排序:值越小优先级越高
132
+
133
+ # 🔧 安全处理 meta,移除 logger 后再 deepcopy
134
+ self._meta = self._safe_deepcopy_meta(meta) if meta is not None else {}
135
+
136
+ self.timeout = self._meta.get('download_timeout', timeout)
137
+ self.proxy = proxy
138
+ self.allow_redirects = allow_redirects
139
+ self.auth = auth
140
+ self.verify = verify
141
+ self.flags = flags or []
142
+ self.encoding = encoding
143
+ self.cb_kwargs = cb_kwargs or {}
144
+ self.body = body
145
+ # 保存高层语义参数(用于 copy)
146
+ self._json_body = json_body
147
+ self._form_data = form_data
148
+
149
+ # 构建 body
150
+ if json_body is not None:
151
+ if 'Content-Type' not in self.headers:
152
+ self.headers['Content-Type'] = 'application/json'
153
+ self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
154
+ if self.method == 'GET':
155
+ self.method = 'POST'
156
+
157
+ elif form_data is not None:
158
+ if self.method == 'GET':
159
+ self.method = 'POST'
160
+ if 'Content-Type' not in self.headers:
161
+ self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
162
+ query_str = urlencode(form_data)
163
+ self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
164
+
165
+
166
+ else:
167
+ # 处理原始 body
168
+ if isinstance(self.body, dict):
169
+ if 'Content-Type' not in self.headers:
170
+ self.headers['Content-Type'] = 'application/json'
171
+ self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
172
+ elif isinstance(self.body, str):
173
+ self.body = self.body.encode(encoding)
174
+
175
+ self.dont_filter = dont_filter
176
+ self._set_url(url)
177
+
178
+ @staticmethod
179
+ def _safe_deepcopy_meta(meta: Dict[str, Any]) -> Dict[str, Any]:
180
+ """安全地 deepcopy meta,移除 logger 后再复制"""
181
+ import logging
182
+
183
+ def clean_logger_recursive(obj):
184
+ """递归移除 logger 对象"""
185
+ if isinstance(obj, logging.Logger):
186
+ return None
187
+ elif isinstance(obj, dict):
188
+ cleaned = {}
189
+ for k, v in obj.items():
190
+ if not (k == 'logger' or isinstance(v, logging.Logger)):
191
+ cleaned[k] = clean_logger_recursive(v)
192
+ return cleaned
193
+ elif isinstance(obj, (list, tuple)):
194
+ cleaned_list = []
195
+ for item in obj:
196
+ cleaned_item = clean_logger_recursive(item)
197
+ if cleaned_item is not None:
198
+ cleaned_list.append(cleaned_item)
199
+ return type(obj)(cleaned_list)
200
+ else:
201
+ return obj
202
+
203
+ # 先清理 logger,再 deepcopy
204
+ cleaned_meta = clean_logger_recursive(meta)
205
+ return deepcopy(cleaned_meta)
206
+
207
+ def copy(self: _Request) -> _Request:
208
+ """
209
+ 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
210
+ """
211
+ return type(self)(
212
+ url=self.url,
213
+ callback=self.callback,
214
+ method=self.method,
215
+ headers=self.headers.copy(),
216
+ body=None, # 由 form_data/json_body 重新生成
217
+ form_data=self._form_data,
218
+ json_body=self._json_body,
219
+ cb_kwargs=deepcopy(self.cb_kwargs),
220
+ err_back=self.err_back,
221
+ cookies=self.cookies.copy(),
222
+ meta=deepcopy(self._meta),
223
+ priority=-self.priority,
224
+ dont_filter=self.dont_filter,
225
+ timeout=self.timeout,
226
+ proxy=self.proxy,
227
+ allow_redirects=self.allow_redirects,
228
+ auth=self.auth,
229
+ verify=self.verify,
230
+ flags=self.flags.copy(),
231
+ encoding=self.encoding
232
+ )
233
+
234
+ def set_meta(self, key: str, value: Any) -> 'Request':
235
+ """设置 meta 中的某个键值,支持链式调用。"""
236
+ self._meta[key] = value
237
+ return self
238
+
239
+ def add_header(self, key: str, value: str) -> 'Request':
240
+ """添加请求头,支持链式调用。"""
241
+ self.headers[key] = value
242
+ return self
243
+
244
+ def add_headers(self, headers: Dict[str, str]) -> 'Request':
245
+ """批量添加请求头,支持链式调用。"""
246
+ self.headers.update(headers)
247
+ return self
248
+
249
+ def set_proxy(self, proxy: str) -> 'Request':
250
+ """设置代理,支持链式调用。"""
251
+ self.proxy = proxy
252
+ return self
253
+
254
+ def set_timeout(self, timeout: float) -> 'Request':
255
+ """设置超时时间,支持链式调用。"""
256
+ self.timeout = timeout
257
+ return self
258
+
259
+ def add_flag(self, flag: str) -> 'Request':
260
+ """添加标记,支持链式调用。"""
261
+ if flag not in self.flags:
262
+ self.flags.append(flag)
263
+ return self
264
+
265
+ def remove_flag(self, flag: str) -> 'Request':
266
+ """移除标记,支持链式调用。"""
267
+ if flag in self.flags:
268
+ self.flags.remove(flag)
269
+ return self
270
+
271
+ def _set_url(self, url: str) -> None:
272
+ """安全设置 URL,确保格式正确。"""
273
+ if not isinstance(url, str):
274
+ raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
275
+
276
+ if not url.strip():
277
+ raise ValueError("URL 不能为空")
278
+
279
+ # 检查危险的 URL scheme
280
+ dangerous_schemes = ['file://', 'ftp://', 'javascript:', 'data:']
281
+ if any(url.lower().startswith(scheme) for scheme in dangerous_schemes):
282
+ raise ValueError(f"URL scheme 不安全: {url[:20]}...")
283
+
284
+ s = safe_url_string(url, self.encoding)
285
+ escaped_url = escape_ajax(s)
286
+
287
+ if not escaped_url.startswith(('http://', 'https://')):
288
+ raise ValueError(f"URL 缺少 HTTP(S) scheme: {escaped_url[:50]}...")
289
+
290
+ # 检查 URL 长度
291
+ if len(escaped_url) > 8192: # 大多数服务器支持的最大 URL 长度
292
+ raise ValueError(f"URL 过长 (超过 8192 字符): {len(escaped_url)} 字符")
293
+
294
+ self._url = escaped_url
295
+
296
+ @property
297
+ def url(self) -> str:
298
+ return self._url
299
+
300
+ @property
301
+ def meta(self) -> Dict[str, Any]:
302
+ return self._meta
303
+
304
+ def __str__(self) -> str:
305
+ return f'<Request url={self.url} method={self.method}>'
306
+
307
+ def __repr__(self) -> str:
308
+ return str(self)
309
+
310
+ def __lt__(self, other: _Request) -> bool:
311
+ """用于按优先级排序"""
312
312
  return self.priority < other.priority