remote.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. # coding=utf-8
  2. """
  3. 远程存储后端(S3 兼容协议)
  4. 支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等
  5. 使用 S3 兼容 API (boto3) 访问对象存储
  6. 数据流程:下载当天 SQLite → 合并新数据 → 上传回远程
  7. """
  8. import pytz
  9. import re
  10. import shutil
  11. import sys
  12. import tempfile
  13. import sqlite3
  14. from datetime import datetime, timedelta
  15. from pathlib import Path
  16. from typing import Dict, List, Optional
  17. try:
  18. import boto3
  19. from botocore.config import Config as BotoConfig
  20. from botocore.exceptions import ClientError
  21. HAS_BOTO3 = True
  22. except ImportError:
  23. HAS_BOTO3 = False
  24. boto3 = None
  25. BotoConfig = None
  26. ClientError = Exception
  27. from trendradar.storage.base import StorageBackend, NewsItem, NewsData, RSSItem, RSSData
  28. from trendradar.storage.sqlite_mixin import SQLiteStorageMixin
  29. from trendradar.utils.time import (
  30. DEFAULT_TIMEZONE,
  31. get_configured_time,
  32. format_date_folder,
  33. format_time_filename,
  34. )
  35. class RemoteStorageBackend(SQLiteStorageMixin, StorageBackend):
  36. """
  37. 远程云存储后端(S3 兼容协议)
  38. 特点:
  39. - 使用 S3 兼容 API 访问远程存储
  40. - 支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等
  41. - 下载 SQLite 到临时目录进行操作
  42. - 支持数据合并和上传
  43. - 支持从远程拉取历史数据到本地
  44. - 运行结束后自动清理临时文件
  45. """
  46. def __init__(
  47. self,
  48. bucket_name: str,
  49. access_key_id: str,
  50. secret_access_key: str,
  51. endpoint_url: str,
  52. region: str = "",
  53. enable_txt: bool = False, # 远程模式默认不生成 TXT
  54. enable_html: bool = True,
  55. temp_dir: Optional[str] = None,
  56. timezone: str = DEFAULT_TIMEZONE,
  57. ):
  58. """
  59. 初始化远程存储后端
  60. Args:
  61. bucket_name: 存储桶名称
  62. access_key_id: 访问密钥 ID
  63. secret_access_key: 访问密钥
  64. endpoint_url: 服务端点 URL
  65. region: 区域(可选,部分服务商需要)
  66. enable_txt: 是否启用 TXT 快照(默认关闭)
  67. enable_html: 是否启用 HTML 报告
  68. temp_dir: 临时目录路径(默认使用系统临时目录)
  69. timezone: 时区配置
  70. """
  71. if not HAS_BOTO3:
  72. raise ImportError("远程存储后端需要安装 boto3: pip install boto3")
  73. self.bucket_name = bucket_name
  74. self.endpoint_url = endpoint_url
  75. self.region = region
  76. self.enable_txt = enable_txt
  77. self.enable_html = enable_html
  78. self.timezone = timezone
  79. # 创建临时目录
  80. self.temp_dir = Path(temp_dir) if temp_dir else Path(tempfile.mkdtemp(prefix="trendradar_"))
  81. self.temp_dir.mkdir(parents=True, exist_ok=True)
  82. # 初始化 S3 客户端
  83. # 使用 virtual-hosted style addressing(主流)
  84. # 根据服务商选择签名版本:
  85. # - 腾讯云 COS 和 阿里云 OSS 使用 SigV2 以避免 chunked encoding 问题
  86. # - 其他服务商(AWS S3、Cloudflare R2、MinIO 等)默认使用 SigV4
  87. use_sigv2 = "myqcloud.com" in endpoint_url.lower() or "aliyuncs.com" in endpoint_url.lower()
  88. signature_version = 's3' if use_sigv2 else 's3v4'
  89. s3_config = BotoConfig(
  90. s3={"addressing_style": "virtual"},
  91. signature_version=signature_version,
  92. )
  93. client_kwargs = {
  94. "endpoint_url": endpoint_url,
  95. "aws_access_key_id": access_key_id,
  96. "aws_secret_access_key": secret_access_key,
  97. "config": s3_config,
  98. }
  99. if region:
  100. client_kwargs["region_name"] = region
  101. self.s3_client = boto3.client("s3", **client_kwargs)
  102. # 跟踪下载的文件(用于清理)
  103. self._downloaded_files: List[Path] = []
  104. self._db_connections: Dict[str, sqlite3.Connection] = {}
  105. print(f"[远程存储] 初始化完成,存储桶: {bucket_name},签名版本: {signature_version}")
  106. @property
  107. def backend_name(self) -> str:
  108. return "remote"
  109. @property
  110. def supports_txt(self) -> bool:
  111. return self.enable_txt
  112. # ========================================
  113. # SQLiteStorageMixin 抽象方法实现
  114. # ========================================
  115. def _get_configured_time(self) -> datetime:
  116. """获取配置时区的当前时间"""
  117. return get_configured_time(self.timezone)
  118. def _format_date_folder(self, date: Optional[str] = None) -> str:
  119. """格式化日期文件夹名 (ISO 格式: YYYY-MM-DD)"""
  120. return format_date_folder(date, self.timezone)
  121. def _format_time_filename(self) -> str:
  122. """格式化时间文件名 (格式: HH-MM)"""
  123. return format_time_filename(self.timezone)
  124. def _get_remote_db_key(self, date: Optional[str] = None, db_type: str = "news") -> str:
  125. """
  126. 获取远程存储中 SQLite 文件的对象键
  127. Args:
  128. date: 日期字符串
  129. db_type: 数据库类型 ("news" 或 "rss")
  130. Returns:
  131. 远程对象键,如 "news/2025-12-28.db" 或 "rss/2025-12-28.db"
  132. """
  133. date_folder = self._format_date_folder(date)
  134. return f"{db_type}/{date_folder}.db"
  135. def _get_local_db_path(self, date: Optional[str] = None, db_type: str = "news") -> Path:
  136. """
  137. 获取本地临时 SQLite 文件路径
  138. Args:
  139. date: 日期字符串
  140. db_type: 数据库类型 ("news" 或 "rss")
  141. Returns:
  142. 本地临时文件路径
  143. """
  144. date_folder = self._format_date_folder(date)
  145. db_dir = self.temp_dir / db_type
  146. db_dir.mkdir(parents=True, exist_ok=True)
  147. return db_dir / f"{date_folder}.db"
  148. def _check_object_exists(self, r2_key: str) -> bool:
  149. """
  150. 检查远程存储中对象是否存在
  151. Args:
  152. r2_key: 远程对象键
  153. Returns:
  154. 是否存在
  155. """
  156. try:
  157. self.s3_client.head_object(Bucket=self.bucket_name, Key=r2_key)
  158. return True
  159. except ClientError as e:
  160. error_code = e.response.get("Error", {}).get("Code", "")
  161. # S3 兼容存储可能返回 404, NoSuchKey, 或其他变体
  162. if error_code in ("404", "NoSuchKey", "Not Found"):
  163. return False
  164. # 其他错误(如权限问题)也视为不存在,但打印警告
  165. print(f"[远程存储] 检查对象存在性失败 ({r2_key}): {e}")
  166. return False
  167. except Exception as e:
  168. print(f"[远程存储] 检查对象存在性异常 ({r2_key}): {e}")
  169. return False
  170. def _download_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> Optional[Path]:
  171. """
  172. 从远程存储下载当天的 SQLite 文件到本地临时目录
  173. 使用 get_object + iter_chunks 替代 download_file,
  174. 以正确处理腾讯云 COS 的 chunked transfer encoding。
  175. Args:
  176. date: 日期字符串
  177. db_type: 数据库类型 ("news" 或 "rss")
  178. Returns:
  179. 本地文件路径,如果不存在返回 None
  180. """
  181. r2_key = self._get_remote_db_key(date, db_type)
  182. local_path = self._get_local_db_path(date, db_type)
  183. # 确保目录存在
  184. local_path.parent.mkdir(parents=True, exist_ok=True)
  185. # 先检查文件是否存在
  186. if not self._check_object_exists(r2_key):
  187. print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}")
  188. return None
  189. try:
  190. # 使用 get_object + iter_chunks 替代 download_file
  191. # iter_chunks 会自动处理 chunked transfer encoding
  192. response = self.s3_client.get_object(Bucket=self.bucket_name, Key=r2_key)
  193. with open(local_path, 'wb') as f:
  194. for chunk in response['Body'].iter_chunks(chunk_size=1024*1024):
  195. f.write(chunk)
  196. self._downloaded_files.append(local_path)
  197. print(f"[远程存储] 已下载: {r2_key} -> {local_path}")
  198. return local_path
  199. except ClientError as e:
  200. error_code = e.response.get("Error", {}).get("Code", "")
  201. # S3 兼容存储可能返回不同的错误码
  202. if error_code in ("404", "NoSuchKey", "Not Found"):
  203. print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}")
  204. return None
  205. else:
  206. print(f"[远程存储] 下载失败 (错误码: {error_code}): {e}")
  207. raise
  208. except Exception as e:
  209. print(f"[远程存储] 下载异常: {e}")
  210. raise
  211. def _upload_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> bool:
  212. """
  213. 上传本地 SQLite 文件到远程存储
  214. Args:
  215. date: 日期字符串
  216. db_type: 数据库类型 ("news" 或 "rss")
  217. Returns:
  218. 是否上传成功
  219. """
  220. local_path = self._get_local_db_path(date, db_type)
  221. r2_key = self._get_remote_db_key(date, db_type)
  222. if not local_path.exists():
  223. print(f"[远程存储] 本地文件不存在,无法上传: {local_path}")
  224. return False
  225. try:
  226. # 获取本地文件大小
  227. local_size = local_path.stat().st_size
  228. print(f"[远程存储] 准备上传: {local_path} ({local_size} bytes) -> {r2_key}")
  229. # 读取文件内容为 bytes 后上传
  230. # 避免传入文件对象时 requests 库使用 chunked transfer encoding
  231. # 腾讯云 COS 等 S3 兼容服务可能无法正确处理 chunked encoding
  232. with open(local_path, 'rb') as f:
  233. file_content = f.read()
  234. # 使用 put_object 并明确设置 ContentLength,确保不使用 chunked encoding
  235. self.s3_client.put_object(
  236. Bucket=self.bucket_name,
  237. Key=r2_key,
  238. Body=file_content,
  239. ContentLength=local_size,
  240. ContentType='application/x-sqlite3',
  241. )
  242. print(f"[远程存储] 已上传: {local_path} -> {r2_key}")
  243. # 验证上传成功
  244. if self._check_object_exists(r2_key):
  245. print(f"[远程存储] 上传验证成功: {r2_key}")
  246. return True
  247. else:
  248. print(f"[远程存储] 上传验证失败: 文件未在远程存储中找到")
  249. return False
  250. except Exception as e:
  251. print(f"[远程存储] 上传失败: {e}")
  252. return False
  253. def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection:
  254. """
  255. 获取数据库连接
  256. Args:
  257. date: 日期字符串
  258. db_type: 数据库类型 ("news" 或 "rss")
  259. Returns:
  260. 数据库连接
  261. """
  262. local_path = self._get_local_db_path(date, db_type)
  263. db_path = str(local_path)
  264. if db_path not in self._db_connections:
  265. # 确保目录存在
  266. local_path.parent.mkdir(parents=True, exist_ok=True)
  267. # 如果本地不存在,尝试从远程存储下载
  268. if not local_path.exists():
  269. self._download_sqlite(date, db_type)
  270. conn = sqlite3.connect(db_path)
  271. conn.row_factory = sqlite3.Row
  272. self._init_tables(conn, db_type)
  273. self._db_connections[db_path] = conn
  274. return self._db_connections[db_path]
  275. # ========================================
  276. # StorageBackend 接口实现(委托给 mixin + 上传)
  277. # ========================================
  278. def save_news_data(self, data: NewsData) -> bool:
  279. """
  280. 保存新闻数据到远程存储
  281. 流程:下载现有数据库 → 插入/更新数据 → 上传回远程存储
  282. """
  283. # 查询已有记录数
  284. conn = self._get_connection(data.date)
  285. cursor = conn.cursor()
  286. cursor.execute("SELECT COUNT(*) as count FROM news_items")
  287. row = cursor.fetchone()
  288. existing_count = row[0] if row else 0
  289. if existing_count > 0:
  290. print(f"[远程存储] 已有 {existing_count} 条历史记录,将合并新数据")
  291. # 使用 mixin 的实现保存数据
  292. success, new_count, updated_count, title_changed_count, off_list_count = \
  293. self._save_news_data_impl(data, "[远程存储]")
  294. if not success:
  295. return False
  296. # 查询合并后的总记录数
  297. cursor.execute("SELECT COUNT(*) as count FROM news_items")
  298. row = cursor.fetchone()
  299. final_count = row[0] if row else 0
  300. # 输出详细的存储统计日志
  301. log_parts = [f"[远程存储] 处理完成:新增 {new_count} 条"]
  302. if updated_count > 0:
  303. log_parts.append(f"更新 {updated_count} 条")
  304. if title_changed_count > 0:
  305. log_parts.append(f"标题变更 {title_changed_count} 条")
  306. if off_list_count > 0:
  307. log_parts.append(f"脱榜 {off_list_count} 条")
  308. log_parts.append(f"(去重后总计: {final_count} 条)")
  309. print(",".join(log_parts))
  310. # 上传到远程存储
  311. if self._upload_sqlite(data.date):
  312. print(f"[远程存储] 数据已同步到远程存储")
  313. return True
  314. else:
  315. print(f"[远程存储] 上传远程存储失败")
  316. return False
  317. def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  318. """获取指定日期的所有新闻数据(合并后)"""
  319. return self._get_today_all_data_impl(date)
  320. def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  321. """获取最新一次抓取的数据"""
  322. return self._get_latest_crawl_data_impl(date)
  323. def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]:
  324. """检测新增的标题"""
  325. return self._detect_new_titles_impl(current_data)
  326. def is_first_crawl_today(self, date: Optional[str] = None) -> bool:
  327. """检查是否是当天第一次抓取"""
  328. return self._is_first_crawl_today_impl(date)
  329. # ========================================
  330. # 时间段执行记录(调度系统)
  331. # ========================================
  332. def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool:
  333. """检查指定时间段的某个 action 是否已执行"""
  334. return self._has_period_executed_impl(date_str, period_key, action)
  335. def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool:
  336. """记录时间段的 action 执行"""
  337. success = self._record_period_execution_impl(date_str, period_key, action)
  338. if success:
  339. now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S")
  340. print(f"[远程存储] 时间段执行记录已保存: {period_key}/{action} at {now_str}")
  341. # 上传到远程存储确保记录持久化
  342. if self._upload_sqlite(date_str):
  343. print(f"[远程存储] 时间段执行记录已同步到远程存储")
  344. return True
  345. else:
  346. print(f"[远程存储] 时间段执行记录同步到远程存储失败")
  347. return False
  348. return False
  349. # ========================================
  350. # RSS 数据存储方法
  351. # ========================================
  352. def save_rss_data(self, data: RSSData) -> bool:
  353. """
  354. 保存 RSS 数据到远程存储
  355. 流程:下载现有数据库 → 插入/更新数据 → 上传回远程存储
  356. """
  357. success, new_count, updated_count = self._save_rss_data_impl(data, "[远程存储]")
  358. if not success:
  359. return False
  360. # 输出统计日志
  361. log_parts = [f"[远程存储] RSS 处理完成:新增 {new_count} 条"]
  362. if updated_count > 0:
  363. log_parts.append(f"更新 {updated_count} 条")
  364. print(",".join(log_parts))
  365. # 上传到远程存储
  366. if self._upload_sqlite(data.date, db_type="rss"):
  367. print(f"[远程存储] RSS 数据已同步到远程存储")
  368. return True
  369. else:
  370. print(f"[远程存储] RSS 上传远程存储失败")
  371. return False
  372. def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]:
  373. """获取指定日期的所有 RSS 数据"""
  374. return self._get_rss_data_impl(date)
  375. def detect_new_rss_items(self, current_data: RSSData) -> Dict[str, List[RSSItem]]:
  376. """检测新增的 RSS 条目"""
  377. return self._detect_new_rss_items_impl(current_data)
  378. def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]:
  379. """获取最新一次抓取的 RSS 数据"""
  380. return self._get_latest_rss_data_impl(date)
  381. # ========================================
  382. # 远程特有功能:TXT/HTML 快照(临时目录)
  383. # ========================================
  384. def save_txt_snapshot(self, data: NewsData) -> Optional[str]:
  385. """保存 TXT 快照(远程存储模式下默认不支持)"""
  386. if not self.enable_txt:
  387. return None
  388. # 如果启用,保存到本地临时目录
  389. try:
  390. date_folder = self._format_date_folder(data.date)
  391. txt_dir = self.temp_dir / date_folder / "txt"
  392. txt_dir.mkdir(parents=True, exist_ok=True)
  393. file_path = txt_dir / f"{data.crawl_time}.txt"
  394. with open(file_path, "w", encoding="utf-8") as f:
  395. for source_id, news_list in data.items.items():
  396. source_name = data.id_to_name.get(source_id, source_id)
  397. if source_name and source_name != source_id:
  398. f.write(f"{source_id} | {source_name}\n")
  399. else:
  400. f.write(f"{source_id}\n")
  401. sorted_news = sorted(news_list, key=lambda x: x.rank)
  402. for item in sorted_news:
  403. line = f"{item.rank}. {item.title}"
  404. if item.url:
  405. line += f" [URL:{item.url}]"
  406. if item.mobile_url:
  407. line += f" [MOBILE:{item.mobile_url}]"
  408. f.write(line + "\n")
  409. f.write("\n")
  410. if data.failed_ids:
  411. f.write("==== 以下ID请求失败 ====\n")
  412. for failed_id in data.failed_ids:
  413. f.write(f"{failed_id}\n")
  414. print(f"[远程存储] TXT 快照已保存: {file_path}")
  415. return str(file_path)
  416. except Exception as e:
  417. print(f"[远程存储] 保存 TXT 快照失败: {e}")
  418. return None
  419. def save_html_report(self, html_content: str, filename: str, is_summary: bool = False) -> Optional[str]:
  420. """保存 HTML 报告到临时目录"""
  421. if not self.enable_html:
  422. return None
  423. try:
  424. date_folder = self._format_date_folder()
  425. html_dir = self.temp_dir / date_folder / "html"
  426. html_dir.mkdir(parents=True, exist_ok=True)
  427. file_path = html_dir / filename
  428. with open(file_path, "w", encoding="utf-8") as f:
  429. f.write(html_content)
  430. print(f"[远程存储] HTML 报告已保存: {file_path}")
  431. return str(file_path)
  432. except Exception as e:
  433. print(f"[远程存储] 保存 HTML 报告失败: {e}")
  434. return None
  435. # ========================================
  436. # 远程特有功能:资源清理
  437. # ========================================
  438. def cleanup(self) -> None:
  439. """清理资源(关闭连接和删除临时文件)"""
  440. # 检查 Python 是否正在关闭
  441. if sys.meta_path is None:
  442. return
  443. # 关闭数据库连接
  444. db_connections = getattr(self, "_db_connections", {})
  445. for db_path, conn in list(db_connections.items()):
  446. try:
  447. conn.close()
  448. print(f"[远程存储] 关闭数据库连接: {db_path}")
  449. except Exception as e:
  450. print(f"[远程存储] 关闭连接失败 {db_path}: {e}")
  451. if db_connections:
  452. db_connections.clear()
  453. # 删除临时目录
  454. temp_dir = getattr(self, "temp_dir", None)
  455. if temp_dir:
  456. try:
  457. if temp_dir.exists():
  458. shutil.rmtree(temp_dir)
  459. print(f"[远程存储] 临时目录已清理: {temp_dir}")
  460. except Exception as e:
  461. # 忽略 Python 关闭时的错误
  462. if sys.meta_path is not None:
  463. print(f"[远程存储] 清理临时目录失败: {e}")
  464. downloaded_files = getattr(self, "_downloaded_files", None)
  465. if downloaded_files:
  466. downloaded_files.clear()
  467. def cleanup_old_data(self, retention_days: int) -> int:
  468. """
  469. 清理远程存储上的过期数据
  470. Args:
  471. retention_days: 保留天数(0 表示不清理)
  472. Returns:
  473. 删除的数据库文件数量
  474. """
  475. if retention_days <= 0:
  476. return 0
  477. deleted_count = 0
  478. cutoff_date = self._get_configured_time() - timedelta(days=retention_days)
  479. try:
  480. # 列出远程存储中 news/ 前缀下的所有对象
  481. paginator = self.s3_client.get_paginator('list_objects_v2')
  482. pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/")
  483. # 收集需要删除的对象键
  484. objects_to_delete = []
  485. deleted_dates = set()
  486. for page in pages:
  487. if 'Contents' not in page:
  488. continue
  489. for obj in page['Contents']:
  490. key = obj['Key']
  491. # 解析日期(格式: news/YYYY-MM-DD.db)
  492. folder_date = None
  493. date_str = None
  494. try:
  495. date_match = re.match(r'news/(\d{4})-(\d{2})-(\d{2})\.db$', key)
  496. if date_match:
  497. folder_date = datetime(
  498. int(date_match.group(1)),
  499. int(date_match.group(2)),
  500. int(date_match.group(3)),
  501. tzinfo=pytz.timezone(self.timezone)
  502. )
  503. date_str = f"{date_match.group(1)}-{date_match.group(2)}-{date_match.group(3)}"
  504. except Exception:
  505. continue
  506. if folder_date and folder_date < cutoff_date:
  507. objects_to_delete.append({'Key': key})
  508. deleted_dates.add(date_str)
  509. # 批量删除对象(每次最多 1000 个)
  510. if objects_to_delete:
  511. batch_size = 1000
  512. for i in range(0, len(objects_to_delete), batch_size):
  513. batch = objects_to_delete[i:i + batch_size]
  514. try:
  515. self.s3_client.delete_objects(
  516. Bucket=self.bucket_name,
  517. Delete={'Objects': batch}
  518. )
  519. print(f"[远程存储] 删除 {len(batch)} 个对象")
  520. except Exception as e:
  521. print(f"[远程存储] 批量删除失败: {e}")
  522. deleted_count = len(deleted_dates)
  523. for date_str in sorted(deleted_dates):
  524. print(f"[远程存储] 清理过期数据: news/{date_str}.db")
  525. print(f"[远程存储] 共清理 {deleted_count} 个过期日期数据库文件")
  526. return deleted_count
  527. except Exception as e:
  528. print(f"[远程存储] 清理过期数据失败: {e}")
  529. return deleted_count
  530. def __del__(self):
  531. """析构函数"""
  532. # 检查 Python 是否正在关闭
  533. if sys.meta_path is None:
  534. return
  535. try:
  536. self.cleanup()
  537. except Exception:
  538. # Python 关闭时可能会出错,忽略即可
  539. pass
  540. # ========================================
  541. # 远程特有功能:数据拉取和列表
  542. # ========================================
  543. def pull_recent_days(self, days: int, local_data_dir: str = "output") -> int:
  544. """
  545. 从远程拉取最近 N 天的数据到本地
  546. Args:
  547. days: 拉取天数
  548. local_data_dir: 本地数据目录
  549. Returns:
  550. 成功拉取的数据库文件数量
  551. """
  552. if days <= 0:
  553. return 0
  554. local_dir = Path(local_data_dir)
  555. local_dir.mkdir(parents=True, exist_ok=True)
  556. pulled_count = 0
  557. now = self._get_configured_time()
  558. print(f"[远程存储] 开始拉取最近 {days} 天的数据...")
  559. for i in range(days):
  560. date = now - timedelta(days=i)
  561. date_str = date.strftime("%Y-%m-%d")
  562. # 本地目标路径
  563. local_date_dir = local_dir / date_str
  564. local_db_path = local_date_dir / "news.db"
  565. # 如果本地已存在,跳过
  566. if local_db_path.exists():
  567. print(f"[远程存储] 跳过(本地已存在): {date_str}")
  568. continue
  569. # 远程对象键
  570. remote_key = f"news/{date_str}.db"
  571. # 检查远程是否存在
  572. if not self._check_object_exists(remote_key):
  573. print(f"[远程存储] 跳过(远程不存在): {date_str}")
  574. continue
  575. # 下载(使用 get_object + iter_chunks 处理 chunked encoding)
  576. try:
  577. local_date_dir.mkdir(parents=True, exist_ok=True)
  578. response = self.s3_client.get_object(Bucket=self.bucket_name, Key=remote_key)
  579. with open(local_db_path, 'wb') as f:
  580. for chunk in response['Body'].iter_chunks(chunk_size=1024*1024):
  581. f.write(chunk)
  582. print(f"[远程存储] 已拉取: {remote_key} -> {local_db_path}")
  583. pulled_count += 1
  584. except Exception as e:
  585. print(f"[远程存储] 拉取失败 ({date_str}): {e}")
  586. print(f"[远程存储] 拉取完成,共下载 {pulled_count} 个数据库文件")
  587. return pulled_count
  588. def list_remote_dates(self) -> List[str]:
  589. """
  590. 列出远程存储中所有可用的日期
  591. Returns:
  592. 日期字符串列表(YYYY-MM-DD 格式)
  593. """
  594. dates = []
  595. try:
  596. paginator = self.s3_client.get_paginator('list_objects_v2')
  597. pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/")
  598. for page in pages:
  599. if 'Contents' not in page:
  600. continue
  601. for obj in page['Contents']:
  602. key = obj['Key']
  603. # 解析日期
  604. date_match = re.match(r'news/(\d{4}-\d{2}-\d{2})\.db$', key)
  605. if date_match:
  606. dates.append(date_match.group(1))
  607. return sorted(dates, reverse=True)
  608. except Exception as e:
  609. print(f"[远程存储] 列出远程日期失败: {e}")
  610. return []