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
@@ -1,192 +1,209 @@
1
- import pickle
2
- import time
3
- import asyncio
4
- from typing import Optional
5
- import redis.asyncio as aioredis
6
-
7
- from crawlo import Request
8
- from crawlo.utils.log import get_logger
9
- from crawlo.utils.request_serializer import RequestSerializer
10
-
11
-
12
- logger = get_logger(__name__)
13
-
14
-
15
- class RedisPriorityQueue:
16
- """
17
- 基于 Redis 的分布式异步优先级队列(生产级优化版)
18
- """
19
-
20
- def __init__(
21
- self,
22
- redis_url: str = "redis://localhost:6379/0",
23
- queue_name: str = "crawlo:requests",
24
- processing_queue: str = "crawlo:processing",
25
- failed_queue: str = "crawlo:failed",
26
- max_retries: int = 3,
27
- timeout: int = 300, # 任务处理超时时间(秒)
28
- max_connections: int = 10, # 连接池大小
29
- ):
30
- self.redis_url = redis_url
31
- self.queue_name = queue_name
32
- self.processing_queue = processing_queue
33
- self.failed_queue = failed_queue
34
- self.max_retries = max_retries
35
- self.timeout = timeout
36
- self.max_connections = max_connections
37
- self._redis = None
38
- self._lock = asyncio.Lock() # 用于连接初始化的锁
39
- self.request_serializer = RequestSerializer() # 处理序列化
40
-
41
- async def connect(self, max_retries=3, delay=1):
42
- """异步连接 Redis,支持重试"""
43
- async with self._lock:
44
- if self._redis is not None:
45
- return self._redis
46
-
47
- for attempt in range(max_retries):
48
- try:
49
- self._redis = await aioredis.from_url(
50
- self.redis_url,
51
- decode_responses=False, # pickle 需要 bytes
52
- max_connections=self.max_connections,
53
- socket_connect_timeout=5,
54
- socket_timeout=30,
55
- )
56
- # 测试连接
57
- await self._redis.ping()
58
- logger.info("✅ Redis 连接成功")
59
- return self._redis
60
- except Exception as e:
61
- logger.warning(f"⚠️ Redis 连接失败 (尝试 {attempt + 1}/{max_retries}): {e}")
62
- if attempt < max_retries - 1:
63
- await asyncio.sleep(delay)
64
- else:
65
- raise ConnectionError(f"❌ 无法连接 Redis: {e}")
66
-
67
- async def _ensure_connection(self):
68
- """确保连接有效"""
69
- if self._redis is None:
70
- await self.connect()
71
- try:
72
- await self._redis.ping()
73
- except Exception:
74
- logger.warning("🔄 Redis 连接失效,尝试重连...")
75
- self._redis = None
76
- await self.connect()
77
-
78
- async def put(self, request: Request, priority: int = 0) -> bool:
79
- """放入请求到队列"""
80
- await self._ensure_connection()
81
- score = -priority
82
- key = self._get_request_key(request)
83
- try:
84
- # 🔥 使用专用的序列化工具清理 Request
85
- clean_request = self.request_serializer.prepare_for_serialization(request)
86
-
87
- serialized = pickle.dumps(clean_request)
88
- pipe = self._redis.pipeline()
89
- pipe.zadd(self.queue_name, {key: score})
90
- pipe.hset(f"{self.queue_name}:data", key, serialized)
91
- result = await pipe.execute()
92
-
93
- if result[0] > 0:
94
- logger.debug(f"✅ 成功入队: {request.url}")
95
- return result[0] > 0
96
- except Exception as e:
97
- logger.error(f"❌ 放入队列失败: {e}")
98
- return False
99
-
100
- async def get(self, timeout: float = 5.0) -> Optional[Request]:
101
- """
102
- 获取请求(带超时)
103
- :param timeout: 最大等待时间(秒),避免无限轮询
104
- """
105
- await self._ensure_connection()
106
- start_time = asyncio.get_event_loop().time()
107
-
108
- while True:
109
- try:
110
- # 尝试获取任务
111
- result = await self._redis.zpopmin(self.queue_name, count=1)
112
- if result:
113
- key, score = result[0]
114
- serialized = await self._redis.hget(f"{self.queue_name}:data", key)
115
- if not serialized:
116
- continue
117
-
118
- # 移动到 processing
119
- processing_key = f"{key}:{int(time.time())}"
120
- pipe = self._redis.pipeline()
121
- pipe.zadd(self.processing_queue, {processing_key: time.time() + self.timeout})
122
- pipe.hset(f"{self.processing_queue}:data", processing_key, serialized)
123
- pipe.hdel(f"{self.queue_name}:data", key)
124
- await pipe.execute()
125
-
126
- return pickle.loads(serialized)
127
-
128
- # 检查是否超时
129
- if asyncio.get_event_loop().time() - start_time > timeout:
130
- return None
131
-
132
- # 短暂等待,避免空轮询
133
- await asyncio.sleep(0.1)
134
-
135
- except Exception as e:
136
- logger.error(f"❌ 获取队列任务失败: {e}")
137
- return None
138
-
139
- async def ack(self, request: Request):
140
- """确认任务完成"""
141
- await self._ensure_connection()
142
- key = self._get_request_key(request)
143
- cursor = 0
144
- while True:
145
- cursor, keys = await self._redis.zscan(self.processing_queue, cursor, match=f"{key}:*")
146
- if keys:
147
- pipe = self._redis.pipeline()
148
- for k in keys:
149
- pipe.zrem(self.processing_queue, k)
150
- pipe.hdel(f"{self.processing_queue}:data", k)
151
- await pipe.execute()
152
- if cursor == 0:
153
- break
154
-
155
- async def fail(self, request: Request, reason: str = ""):
156
- """标记任务失败"""
157
- await self._ensure_connection()
158
- key = self._get_request_key(request)
159
- await self.ack(request)
160
-
161
- retry_key = f"{self.failed_queue}:retries:{key}"
162
- retries = await self._redis.incr(retry_key)
163
- await self._redis.expire(retry_key, 86400)
164
-
165
- if retries <= self.max_retries:
166
- await self.put(request, priority=request.priority + 1)
167
- logger.info(f"🔁 任务重试 [{retries}/{self.max_retries}]: {request.url}")
168
- else:
169
- failed_data = {
170
- "url": request.url,
171
- "reason": reason,
172
- "retries": retries,
173
- "failed_at": time.time(),
174
- "request_pickle": pickle.dumps(request).hex(), # 可选:保存完整请求
175
- }
176
- await self._redis.lpush(self.failed_queue, pickle.dumps(failed_data))
177
- logger.error(f"❌ 任务彻底失败 [{retries}次]: {request.url}")
178
-
179
- def _get_request_key(self, request: Request) -> str:
180
- """生成请求唯一键"""
181
- return f"url:{hash(request.url)}"
182
-
183
- async def qsize(self) -> int:
184
- """获取队列大小"""
185
- await self._ensure_connection()
186
- return await self._redis.zcard(self.queue_name)
187
-
188
- async def close(self):
189
- """关闭连接"""
190
- if self._redis:
191
- await self._redis.close()
1
+ import pickle
2
+ import time
3
+ import asyncio
4
+ from typing import Optional
5
+ import redis.asyncio as aioredis
6
+ import traceback
7
+ import os
8
+
9
+ from crawlo import Request
10
+ from crawlo.utils.log import get_logger
11
+ from crawlo.utils.request_serializer import RequestSerializer
12
+
13
+
14
+ logger = get_logger(__name__)
15
+
16
+
17
+ class RedisPriorityQueue:
18
+ """
19
+ 基于 Redis 的分布式异步优先级队列(生产级优化版)
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ redis_url: str = None,
25
+ queue_name: str = "crawlo:requests",
26
+ processing_queue: str = "crawlo:processing",
27
+ failed_queue: str = "crawlo:failed",
28
+ max_retries: int = 3,
29
+ timeout: int = 300, # 任务处理超时时间(秒)
30
+ max_connections: int = 10, # 连接池大小
31
+ ):
32
+ # 如果没有提供 redis_url,则从环境变量构造
33
+ if redis_url is None:
34
+ redis_host = os.getenv('REDIS_HOST', 'localhost')
35
+ redis_port = os.getenv('REDIS_PORT', '6379')
36
+ redis_db = os.getenv('REDIS_DB', '0')
37
+ redis_password = os.getenv('REDIS_PASSWORD', '')
38
+
39
+ if redis_password:
40
+ redis_url = f"redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}"
41
+ else:
42
+ redis_url = f"redis://{redis_host}:{redis_port}/{redis_db}"
43
+
44
+ self.redis_url = redis_url
45
+ self.queue_name = queue_name
46
+ self.processing_queue = processing_queue
47
+ self.failed_queue = failed_queue
48
+ self.max_retries = max_retries
49
+ self.timeout = timeout
50
+ self.max_connections = max_connections
51
+ self._redis = None
52
+ self._lock = asyncio.Lock() # 用于连接初始化的锁
53
+ self.request_serializer = RequestSerializer() # 处理序列化
54
+
55
+ async def connect(self, max_retries=3, delay=1):
56
+ """异步连接 Redis,支持重试"""
57
+ async with self._lock:
58
+ if self._redis is not None:
59
+ return self._redis
60
+
61
+ for attempt in range(max_retries):
62
+ try:
63
+ self._redis = await aioredis.from_url(
64
+ self.redis_url,
65
+ decode_responses=False, # pickle 需要 bytes
66
+ max_connections=self.max_connections,
67
+ socket_connect_timeout=5,
68
+ socket_timeout=30,
69
+ )
70
+ # 测试连接
71
+ await self._redis.ping()
72
+ logger.info("✅ Redis 连接成功")
73
+ return self._redis
74
+ except Exception as e:
75
+ logger.warning(f"⚠️ Redis 连接失败 (尝试 {attempt + 1}/{max_retries}): {e}")
76
+ logger.warning(f"详细错误信息:\n{traceback.format_exc()}")
77
+ if attempt < max_retries - 1:
78
+ await asyncio.sleep(delay)
79
+ else:
80
+ raise ConnectionError(f"❌ 无法连接 Redis: {e}")
81
+
82
+ async def _ensure_connection(self):
83
+ """确保连接有效"""
84
+ if self._redis is None:
85
+ await self.connect()
86
+ try:
87
+ await self._redis.ping()
88
+ except Exception as e:
89
+ logger.warning(f"🔄 Redis 连接失效,尝试重连...: {e}")
90
+ self._redis = None
91
+ await self.connect()
92
+
93
+ async def put(self, request: Request, priority: int = 0) -> bool:
94
+ """放入请求到队列"""
95
+ await self._ensure_connection()
96
+ score = -priority
97
+ key = self._get_request_key(request)
98
+ try:
99
+ # 🔥 使用专用的序列化工具清理 Request
100
+ clean_request = self.request_serializer.prepare_for_serialization(request)
101
+
102
+ serialized = pickle.dumps(clean_request)
103
+ pipe = self._redis.pipeline()
104
+ pipe.zadd(self.queue_name, {key: score})
105
+ pipe.hset(f"{self.queue_name}:data", key, serialized)
106
+ result = await pipe.execute()
107
+
108
+ if result[0] > 0:
109
+ logger.debug(f"✅ 成功入队: {request.url}")
110
+ return result[0] > 0
111
+ except Exception as e:
112
+ logger.error(f"❌ 放入队列失败: {e}")
113
+ logger.error(f"详细错误信息:\n{traceback.format_exc()}")
114
+ return False
115
+
116
+ async def get(self, timeout: float = 5.0) -> Optional[Request]:
117
+ """
118
+ 获取请求(带超时)
119
+ :param timeout: 最大等待时间(秒),避免无限轮询
120
+ """
121
+ await self._ensure_connection()
122
+ start_time = asyncio.get_event_loop().time()
123
+
124
+ while True:
125
+ try:
126
+ # 尝试获取任务
127
+ result = await self._redis.zpopmin(self.queue_name, count=1)
128
+ if result:
129
+ key, score = result[0]
130
+ serialized = await self._redis.hget(f"{self.queue_name}:data", key)
131
+ if not serialized:
132
+ continue
133
+
134
+ # 移动到 processing
135
+ processing_key = f"{key}:{int(time.time())}"
136
+ pipe = self._redis.pipeline()
137
+ pipe.zadd(self.processing_queue, {processing_key: time.time() + self.timeout})
138
+ pipe.hset(f"{self.processing_queue}:data", processing_key, serialized)
139
+ pipe.hdel(f"{self.queue_name}:data", key)
140
+ await pipe.execute()
141
+
142
+ return pickle.loads(serialized)
143
+
144
+ # 检查是否超时
145
+ if asyncio.get_event_loop().time() - start_time > timeout:
146
+ return None
147
+
148
+ # 短暂等待,避免空轮询
149
+ await asyncio.sleep(0.1)
150
+
151
+ except Exception as e:
152
+ logger.error(f"❌ 获取队列任务失败: {e}")
153
+ logger.error(f"详细错误信息:\n{traceback.format_exc()}")
154
+ return None
155
+
156
+ async def ack(self, request: Request):
157
+ """确认任务完成"""
158
+ await self._ensure_connection()
159
+ key = self._get_request_key(request)
160
+ cursor = 0
161
+ while True:
162
+ cursor, keys = await self._redis.zscan(self.processing_queue, cursor, match=f"{key}:*")
163
+ if keys:
164
+ pipe = self._redis.pipeline()
165
+ for k in keys:
166
+ pipe.zrem(self.processing_queue, k)
167
+ pipe.hdel(f"{self.processing_queue}:data", k)
168
+ await pipe.execute()
169
+ if cursor == 0:
170
+ break
171
+
172
+ async def fail(self, request: Request, reason: str = ""):
173
+ """标记任务失败"""
174
+ await self._ensure_connection()
175
+ key = self._get_request_key(request)
176
+ await self.ack(request)
177
+
178
+ retry_key = f"{self.failed_queue}:retries:{key}"
179
+ retries = await self._redis.incr(retry_key)
180
+ await self._redis.expire(retry_key, 86400)
181
+
182
+ if retries <= self.max_retries:
183
+ await self.put(request, priority=request.priority + 1)
184
+ logger.info(f"🔁 任务重试 [{retries}/{self.max_retries}]: {request.url}")
185
+ else:
186
+ failed_data = {
187
+ "url": request.url,
188
+ "reason": reason,
189
+ "retries": retries,
190
+ "failed_at": time.time(),
191
+ "request_pickle": pickle.dumps(request).hex(), # 可选:保存完整请求
192
+ }
193
+ await self._redis.lpush(self.failed_queue, pickle.dumps(failed_data))
194
+ logger.error(f"❌ 任务彻底失败 [{retries}次]: {request.url}")
195
+
196
+ def _get_request_key(self, request: Request) -> str:
197
+ """生成请求唯一键"""
198
+ return f"url:{hash(request.url)}"
199
+
200
+ async def qsize(self) -> int:
201
+ """获取队列大小"""
202
+ await self._ensure_connection()
203
+ return await self._redis.zcard(self.queue_name)
204
+
205
+ async def close(self):
206
+ """关闭连接"""
207
+ if self._redis:
208
+ await self._redis.close()
192
209
  self._redis = None
@@ -1,7 +1,7 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- """
4
- # @Time : 2025-05-11 11:08
5
- # @Author : oscar
6
- # @Desc : None
7
- """
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ """
4
+ # @Time : 2025-05-11 11:08
5
+ # @Author : oscar
6
+ # @Desc : None
7
+ """