crawlo 1.1.1__py3-none-any.whl → 1.1.2__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 (68) hide show
  1. crawlo/__init__.py +2 -1
  2. crawlo/__version__.py +1 -1
  3. crawlo/commands/genspider.py +68 -42
  4. crawlo/commands/list.py +102 -93
  5. crawlo/commands/startproject.py +89 -4
  6. crawlo/commands/utils.py +187 -0
  7. crawlo/config.py +280 -0
  8. crawlo/core/engine.py +16 -3
  9. crawlo/core/enhanced_engine.py +190 -0
  10. crawlo/core/scheduler.py +113 -8
  11. crawlo/crawler.py +840 -307
  12. crawlo/downloader/__init__.py +181 -17
  13. crawlo/downloader/aiohttp_downloader.py +15 -2
  14. crawlo/downloader/cffi_downloader.py +11 -1
  15. crawlo/downloader/httpx_downloader.py +14 -3
  16. crawlo/filters/__init__.py +122 -5
  17. crawlo/filters/aioredis_filter.py +128 -36
  18. crawlo/filters/memory_filter.py +99 -32
  19. crawlo/middleware/proxy.py +11 -8
  20. crawlo/middleware/retry.py +40 -5
  21. crawlo/mode_manager.py +201 -0
  22. crawlo/network/__init__.py +17 -3
  23. crawlo/network/request.py +118 -10
  24. crawlo/network/response.py +131 -28
  25. crawlo/pipelines/__init__.py +1 -1
  26. crawlo/pipelines/csv_pipeline.py +317 -0
  27. crawlo/pipelines/json_pipeline.py +219 -0
  28. crawlo/queue/__init__.py +0 -0
  29. crawlo/queue/pqueue.py +37 -0
  30. crawlo/queue/queue_manager.py +304 -0
  31. crawlo/queue/redis_priority_queue.py +192 -0
  32. crawlo/settings/default_settings.py +68 -9
  33. crawlo/spider/__init__.py +576 -66
  34. crawlo/task_manager.py +4 -1
  35. crawlo/templates/project/middlewares.py.tmpl +56 -45
  36. crawlo/templates/project/pipelines.py.tmpl +308 -36
  37. crawlo/templates/project/run.py.tmpl +239 -0
  38. crawlo/templates/project/settings.py.tmpl +211 -17
  39. crawlo/templates/spider/spider.py.tmpl +153 -7
  40. crawlo/utils/controlled_spider_mixin.py +336 -0
  41. crawlo/utils/large_scale_config.py +287 -0
  42. crawlo/utils/large_scale_helper.py +344 -0
  43. crawlo/utils/queue_helper.py +176 -0
  44. crawlo/utils/request_serializer.py +220 -0
  45. crawlo-1.1.2.dist-info/METADATA +567 -0
  46. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/RECORD +54 -46
  47. tests/test_final_validation.py +154 -0
  48. tests/test_redis_config.py +29 -0
  49. tests/test_redis_queue.py +225 -0
  50. tests/test_request_serialization.py +71 -0
  51. tests/test_scheduler.py +242 -0
  52. crawlo/pipelines/mysql_batch_pipline.py +0 -273
  53. crawlo/utils/pqueue.py +0 -174
  54. crawlo-1.1.1.dist-info/METADATA +0 -220
  55. examples/baidu_spider/__init__.py +0 -7
  56. examples/baidu_spider/demo.py +0 -94
  57. examples/baidu_spider/items.py +0 -46
  58. examples/baidu_spider/middleware.py +0 -49
  59. examples/baidu_spider/pipeline.py +0 -55
  60. examples/baidu_spider/run.py +0 -27
  61. examples/baidu_spider/settings.py +0 -121
  62. examples/baidu_spider/spiders/__init__.py +0 -7
  63. examples/baidu_spider/spiders/bai_du.py +0 -61
  64. examples/baidu_spider/spiders/miit.py +0 -159
  65. examples/baidu_spider/spiders/sina.py +0 -79
  66. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
  67. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
  68. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,220 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ Request 序列化工具类
5
+ 负责处理 Request 对象的序列化前清理工作,解决 logger 等不可序列化对象的问题
6
+ """
7
+ import logging
8
+ import pickle
9
+ import gc
10
+ from typing import Any, Dict
11
+
12
+ from crawlo.utils.log import get_logger
13
+
14
+
15
+ class RequestSerializer:
16
+ """Request 序列化工具类"""
17
+
18
+ def __init__(self):
19
+ self.logger = get_logger(self.__class__.__name__)
20
+
21
+ def prepare_for_serialization(self, request):
22
+ """
23
+ 为序列化准备 Request 对象
24
+ 移除不可序列化的属性,保存必要信息用于恢复
25
+ """
26
+ try:
27
+ # 处理 callback
28
+ self._handle_callback(request)
29
+
30
+ # 清理 meta 中的 logger
31
+ if hasattr(request, 'meta') and request.meta:
32
+ self._clean_dict_recursive(request.meta)
33
+
34
+ # 清理 cb_kwargs 中的 logger
35
+ if hasattr(request, 'cb_kwargs') and request.cb_kwargs:
36
+ self._clean_dict_recursive(request.cb_kwargs)
37
+
38
+ # 清理其他可能的 logger 引用
39
+ for attr_name in ['headers', 'cookies']:
40
+ if hasattr(request, attr_name):
41
+ attr_value = getattr(request, attr_name)
42
+ if isinstance(attr_value, dict):
43
+ self._clean_dict_recursive(attr_value)
44
+
45
+ # 最终验证
46
+ if not self._test_serialization(request):
47
+ self.logger.warning("⚠️ 常规清理无效,使用深度清理")
48
+ request = self._deep_clean_request(request)
49
+
50
+ return request
51
+
52
+ except Exception as e:
53
+ self.logger.error(f"❌ Request 序列化准备失败: {e}")
54
+ # 最后的保险:重建 Request
55
+ return self._rebuild_clean_request(request)
56
+
57
+ def restore_after_deserialization(self, request, spider=None):
58
+ """
59
+ 反序列化后恢复 Request 对象
60
+ 恢复 callback 等必要信息
61
+ """
62
+ if not request:
63
+ return request
64
+
65
+ # 恢复 callback
66
+ if hasattr(request, 'meta') and '_callback_info' in request.meta:
67
+ callback_info = request.meta.pop('_callback_info')
68
+
69
+ if spider:
70
+ spider_class_name = callback_info.get('spider_class')
71
+ method_name = callback_info.get('method_name')
72
+
73
+ if (spider.__class__.__name__ == spider_class_name and
74
+ hasattr(spider, method_name)):
75
+ request.callback = getattr(spider, method_name)
76
+
77
+ # 确保 spider 有有效的 logger
78
+ if not hasattr(spider, 'logger') or spider.logger is None:
79
+ spider.logger = get_logger(spider.name or spider.__class__.__name__)
80
+
81
+ return request
82
+
83
+ def _handle_callback(self, request):
84
+ """处理 callback 相关的清理"""
85
+ if hasattr(request, 'callback') and request.callback is not None:
86
+ callback = request.callback
87
+
88
+ # 如果是绑定方法,保存信息并移除引用
89
+ if hasattr(callback, '__self__') and hasattr(callback, '__name__'):
90
+ spider_instance = callback.__self__
91
+
92
+ # 保存 callback 信息
93
+ if not hasattr(request, 'meta') or request.meta is None:
94
+ request.meta = {}
95
+ request.meta['_callback_info'] = {
96
+ 'spider_class': spider_instance.__class__.__name__,
97
+ 'method_name': callback.__name__
98
+ }
99
+
100
+ # 移除 callback 引用
101
+ request.callback = None
102
+
103
+ def _clean_dict_recursive(self, data, depth=0):
104
+ """递归清理字典中的 logger"""
105
+ if depth > 5 or not isinstance(data, dict):
106
+ return
107
+
108
+ keys_to_remove = []
109
+ for key, value in list(data.items()):
110
+ if isinstance(value, logging.Logger):
111
+ keys_to_remove.append(key)
112
+ elif isinstance(key, str) and 'logger' in key.lower():
113
+ keys_to_remove.append(key)
114
+ elif isinstance(value, dict):
115
+ self._clean_dict_recursive(value, depth + 1)
116
+ elif isinstance(value, (list, tuple)):
117
+ for item in value:
118
+ if isinstance(item, dict):
119
+ self._clean_dict_recursive(item, depth + 1)
120
+
121
+ for key in keys_to_remove:
122
+ data.pop(key, None)
123
+
124
+ def _test_serialization(self, request):
125
+ """测试是否可以序列化"""
126
+ try:
127
+ pickle.dumps(request)
128
+ return True
129
+ except Exception:
130
+ return False
131
+
132
+ def _deep_clean_request(self, request):
133
+ """深度清理 Request 对象"""
134
+ import logging
135
+
136
+ def recursive_clean(target, visited=None, depth=0):
137
+ if depth > 5 or not target:
138
+ return
139
+ if visited is None:
140
+ visited = set()
141
+
142
+ obj_id = id(target)
143
+ if obj_id in visited:
144
+ return
145
+ visited.add(obj_id)
146
+
147
+ # 处理对象属性
148
+ if hasattr(target, '__dict__'):
149
+ attrs_to_clean = []
150
+ for attr_name, attr_value in list(target.__dict__.items()):
151
+ if isinstance(attr_value, logging.Logger):
152
+ attrs_to_clean.append(attr_name)
153
+ elif isinstance(attr_name, str) and 'logger' in attr_name.lower():
154
+ attrs_to_clean.append(attr_name)
155
+ elif hasattr(attr_value, '__dict__'):
156
+ recursive_clean(attr_value, visited, depth + 1)
157
+
158
+ for attr_name in attrs_to_clean:
159
+ try:
160
+ setattr(target, attr_name, None)
161
+ except (AttributeError, TypeError):
162
+ pass
163
+
164
+ # 处理字典
165
+ elif isinstance(target, dict):
166
+ self._clean_dict_recursive(target, depth)
167
+
168
+ recursive_clean(request)
169
+ gc.collect()
170
+ return request
171
+
172
+ def _rebuild_clean_request(self, original_request):
173
+ """重建一个干净的 Request 对象"""
174
+ from crawlo.network.request import Request
175
+
176
+ try:
177
+ # 提取安全的属性
178
+ safe_meta = {}
179
+ if hasattr(original_request, 'meta') and original_request.meta:
180
+ for key, value in original_request.meta.items():
181
+ if not isinstance(value, logging.Logger):
182
+ try:
183
+ pickle.dumps(value)
184
+ safe_meta[key] = value
185
+ except Exception:
186
+ try:
187
+ safe_meta[key] = str(value)
188
+ except Exception:
189
+ continue
190
+
191
+ # 安全地获取其他属性
192
+ safe_headers = {}
193
+ if hasattr(original_request, 'headers') and original_request.headers:
194
+ for k, v in original_request.headers.items():
195
+ try:
196
+ safe_headers[str(k)] = str(v)
197
+ except Exception:
198
+ continue
199
+
200
+ # 创建干净的 Request
201
+ clean_request = Request(
202
+ url=str(original_request.url),
203
+ method=getattr(original_request, 'method', 'GET'),
204
+ headers=safe_headers,
205
+ meta=safe_meta,
206
+ priority=-getattr(original_request, 'priority', 0),
207
+ dont_filter=getattr(original_request, 'dont_filter', False),
208
+ timeout=getattr(original_request, 'timeout', None),
209
+ encoding=getattr(original_request, 'encoding', 'utf-8')
210
+ )
211
+
212
+ # 验证新 Request 可以序列化
213
+ pickle.dumps(clean_request)
214
+ return clean_request
215
+
216
+ except Exception as e:
217
+ self.logger.error(f"❌ 重建 Request 失败: {e}")
218
+ # 最简单的 fallback
219
+ from crawlo.network.request import Request
220
+ return Request(url=str(original_request.url))