crawlo 1.1.2__py3-none-any.whl → 1.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of crawlo might be problematic. Click here for more details.

Files changed (113) 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 +166 -162
  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 -257
  23. crawlo/event.py +11 -11
  24. crawlo/exceptions.py +82 -78
  25. crawlo/extension/__init__.py +31 -31
  26. crawlo/extension/log_interval.py +49 -49
  27. crawlo/extension/log_stats.py +44 -44
  28. crawlo/extension/logging_extension.py +34 -34
  29. crawlo/filters/__init__.py +154 -154
  30. crawlo/filters/aioredis_filter.py +242 -242
  31. crawlo/filters/memory_filter.py +269 -269
  32. crawlo/items/__init__.py +23 -23
  33. crawlo/items/base.py +21 -21
  34. crawlo/items/fields.py +53 -53
  35. crawlo/items/items.py +104 -104
  36. crawlo/middleware/__init__.py +21 -21
  37. crawlo/middleware/default_header.py +32 -32
  38. crawlo/middleware/download_delay.py +28 -28
  39. crawlo/middleware/middleware_manager.py +135 -135
  40. crawlo/middleware/proxy.py +248 -248
  41. crawlo/middleware/request_ignore.py +30 -30
  42. crawlo/middleware/response_code.py +18 -18
  43. crawlo/middleware/response_filter.py +26 -26
  44. crawlo/middleware/retry.py +125 -125
  45. crawlo/mode_manager.py +200 -200
  46. crawlo/network/__init__.py +21 -21
  47. crawlo/network/request.py +311 -311
  48. crawlo/network/response.py +271 -269
  49. crawlo/pipelines/__init__.py +22 -13
  50. crawlo/pipelines/bloom_dedup_pipeline.py +157 -0
  51. crawlo/pipelines/console_pipeline.py +39 -39
  52. crawlo/pipelines/csv_pipeline.py +316 -316
  53. crawlo/pipelines/database_dedup_pipeline.py +225 -0
  54. crawlo/pipelines/json_pipeline.py +218 -218
  55. crawlo/pipelines/memory_dedup_pipeline.py +116 -0
  56. crawlo/pipelines/mongo_pipeline.py +116 -116
  57. crawlo/pipelines/mysql_pipeline.py +195 -195
  58. crawlo/pipelines/pipeline_manager.py +56 -56
  59. crawlo/pipelines/redis_dedup_pipeline.py +163 -0
  60. crawlo/project.py +153 -153
  61. crawlo/queue/pqueue.py +37 -37
  62. crawlo/queue/queue_manager.py +307 -303
  63. crawlo/queue/redis_priority_queue.py +208 -191
  64. crawlo/settings/__init__.py +7 -7
  65. crawlo/settings/default_settings.py +245 -226
  66. crawlo/settings/setting_manager.py +99 -99
  67. crawlo/spider/__init__.py +639 -639
  68. crawlo/stats_collector.py +59 -59
  69. crawlo/subscriber.py +106 -106
  70. crawlo/task_manager.py +30 -30
  71. crawlo/templates/crawlo.cfg.tmpl +10 -10
  72. crawlo/templates/project/__init__.py.tmpl +3 -3
  73. crawlo/templates/project/items.py.tmpl +17 -17
  74. crawlo/templates/project/middlewares.py.tmpl +86 -86
  75. crawlo/templates/project/pipelines.py.tmpl +341 -335
  76. crawlo/templates/project/run.py.tmpl +251 -238
  77. crawlo/templates/project/settings.py.tmpl +250 -247
  78. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  79. crawlo/templates/spider/spider.py.tmpl +177 -177
  80. crawlo/utils/__init__.py +7 -7
  81. crawlo/utils/controlled_spider_mixin.py +439 -335
  82. crawlo/utils/date_tools.py +233 -233
  83. crawlo/utils/db_helper.py +343 -343
  84. crawlo/utils/func_tools.py +82 -82
  85. crawlo/utils/large_scale_config.py +286 -286
  86. crawlo/utils/large_scale_helper.py +343 -343
  87. crawlo/utils/log.py +128 -128
  88. crawlo/utils/queue_helper.py +175 -175
  89. crawlo/utils/request.py +267 -267
  90. crawlo/utils/request_serializer.py +219 -219
  91. crawlo/utils/spider_loader.py +62 -62
  92. crawlo/utils/system.py +11 -11
  93. crawlo/utils/tools.py +4 -4
  94. crawlo/utils/url.py +39 -39
  95. {crawlo-1.1.2.dist-info → crawlo-1.1.3.dist-info}/METADATA +635 -567
  96. crawlo-1.1.3.dist-info/RECORD +113 -0
  97. examples/__init__.py +7 -7
  98. examples/controlled_spider_example.py +205 -0
  99. tests/__init__.py +7 -7
  100. tests/test_final_validation.py +153 -153
  101. tests/test_proxy_health_check.py +32 -32
  102. tests/test_proxy_middleware_integration.py +136 -136
  103. tests/test_proxy_providers.py +56 -56
  104. tests/test_proxy_stats.py +19 -19
  105. tests/test_proxy_strategies.py +59 -59
  106. tests/test_redis_config.py +28 -28
  107. tests/test_redis_queue.py +224 -224
  108. tests/test_request_serialization.py +70 -70
  109. tests/test_scheduler.py +241 -241
  110. crawlo-1.1.2.dist-info/RECORD +0 -108
  111. {crawlo-1.1.2.dist-info → crawlo-1.1.3.dist-info}/WHEEL +0 -0
  112. {crawlo-1.1.2.dist-info → crawlo-1.1.3.dist-info}/entry_points.txt +0 -0
  113. {crawlo-1.1.2.dist-info → crawlo-1.1.3.dist-info}/top_level.txt +0 -0
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
- from crawlo.utils.log import get_logger
20
-
21
-
22
- _Request = TypeVar("_Request", bound="Request")
23
-
24
-
25
- class RequestPriority:
26
- """请求优先级常量和工具类"""
27
- URGENT = -200 # 紧急任务
28
- HIGH = -100 # 高优先级
29
- NORMAL = 0 # 正常优先级(默认)
30
- LOW = 100 # 低优先级
31
- BACKGROUND = 200 # 后台任务
32
-
33
- @classmethod
34
- def get_all_priorities(cls) -> Dict[str, int]:
35
- """获取所有优先级常量"""
36
- return {
37
- 'URGENT': cls.URGENT,
38
- 'HIGH': cls.HIGH,
39
- 'NORMAL': cls.NORMAL,
40
- 'LOW': cls.LOW,
41
- 'BACKGROUND': cls.BACKGROUND
42
- }
43
-
44
- @classmethod
45
- def from_string(cls, priority_str: str) -> int:
46
- """从字符串获取优先级值"""
47
- priorities = cls.get_all_priorities()
48
- if priority_str.upper() not in priorities:
49
- raise ValueError(f"不支持的优先级: {priority_str}, 支持: {list(priorities.keys())}")
50
- return priorities[priority_str.upper()]
51
-
52
-
53
- class Request:
54
- """
55
- 封装一个 HTTP 请求对象,用于爬虫框架中表示一个待抓取的请求任务。
56
- 支持 JSON、表单、原始 body 提交,自动处理 Content-Type 与编码。
57
- 不支持文件上传(multipart/form-data),保持轻量。
58
- """
59
-
60
- __slots__ = (
61
- '_url',
62
- '_meta',
63
- 'callback',
64
- 'cb_kwargs',
65
- 'err_back',
66
- 'headers',
67
- 'body',
68
- 'method',
69
- 'cookies',
70
- 'priority',
71
- 'encoding',
72
- 'dont_filter',
73
- 'timeout',
74
- 'proxy',
75
- 'allow_redirects',
76
- 'auth',
77
- 'verify',
78
- 'flags',
79
- '_json_body',
80
- '_form_data'
81
- )
82
-
83
- def __init__(
84
- self,
85
- url: str,
86
- callback: Optional[Callable] = None,
87
- method: Optional[str] = 'GET',
88
- headers: Optional[Dict[str, str]] = None,
89
- body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
90
- form_data: Optional[Dict[Any, Any]] = None,
91
- json_body: Optional[Dict[Any, Any]] = None,
92
- cb_kwargs: Optional[Dict[str, Any]] = None,
93
- cookies: Optional[Dict[str, str]] = None,
94
- meta: Optional[Dict[str, Any]] = None,
95
- priority: int = RequestPriority.NORMAL,
96
- dont_filter: bool = False,
97
- timeout: Optional[float] = None,
98
- proxy: Optional[str] = None,
99
- allow_redirects: bool = True,
100
- auth: Optional[tuple] = None,
101
- verify: bool = True,
102
- flags: Optional[List[str]] = None,
103
- encoding: str = 'utf-8'
104
- ):
105
- """
106
- 初始化请求对象。
107
-
108
- :param url: 请求 URL(必须)
109
- :param callback: 成功回调函数
110
- :param method: HTTP 方法,默认 GET
111
- :param headers: 请求头
112
- :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
113
- :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
114
- :param json_body: JSON 数据,自动序列化并设置 Content-Type
115
- :param cb_kwargs: 传递给 callback 的额外参数
116
- :param cookies: Cookies 字典
117
- :param meta: 元数据(跨中间件传递数据)
118
- :param priority: 优先级(数值越小越优先)
119
- :param dont_filter: 是否跳过去重
120
- :param timeout: 超时时间(秒)
121
- :param proxy: 代理地址,如 http://127.0.0.1:8080
122
- :param allow_redirects: 是否允许重定向
123
- :param auth: 认证元组 (username, password)
124
- :param verify: 是否验证 SSL 证书
125
- :param flags: 标记(用于调试或分类)
126
- :param encoding: 字符编码,默认 utf-8
127
- """
128
- self.callback = callback
129
- self.method = str(method).upper()
130
- self.headers = headers or {}
131
- self.cookies = cookies or {}
132
- self.priority = -priority # 用于排序:值越小优先级越高
133
-
134
- # 🔧 安全处理 meta,移除 logger 后再 deepcopy
135
- self._meta = self._safe_deepcopy_meta(meta) if meta is not None else {}
136
-
137
- self.timeout = self._meta.get('download_timeout', timeout)
138
- self.proxy = proxy
139
- self.allow_redirects = allow_redirects
140
- self.auth = auth
141
- self.verify = verify
142
- self.flags = flags or []
143
- self.encoding = encoding
144
- self.cb_kwargs = cb_kwargs or {}
145
- self.body = body
146
- # 保存高层语义参数(用于 copy)
147
- self._json_body = json_body
148
- self._form_data = form_data
149
-
150
- # 构建 body
151
- if json_body is not None:
152
- if 'Content-Type' not in self.headers:
153
- self.headers['Content-Type'] = 'application/json'
154
- self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
155
- if self.method == 'GET':
156
- self.method = 'POST'
157
-
158
- elif form_data is not None:
159
- if self.method == 'GET':
160
- self.method = 'POST'
161
- if 'Content-Type' not in self.headers:
162
- self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
163
- query_str = urlencode(form_data)
164
- self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
165
-
166
-
167
- else:
168
- # 处理原始 body
169
- if isinstance(self.body, dict):
170
- if 'Content-Type' not in self.headers:
171
- self.headers['Content-Type'] = 'application/json'
172
- self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
173
- elif isinstance(self.body, str):
174
- self.body = self.body.encode(encoding)
175
-
176
- self.dont_filter = dont_filter
177
- self._set_url(url)
178
-
179
- def _safe_deepcopy_meta(self, 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