daily_cache_store.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """每日缓存存储 —— arXiv 原始数据本地缓存以避免重复拉取."""
  2. from __future__ import annotations
  3. import json
  4. import sqlite3
  5. import time
  6. from typing import Any
  7. from ...utils.common import exec_sql
  8. def ensure_tables(db_path: str) -> None:
  9. exec_sql(db_path,
  10. """CREATE TABLE IF NOT EXISTS daily_papers_cache (
  11. date_key TEXT NOT NULL,
  12. cache_key TEXT NOT NULL,
  13. payload_json TEXT NOT NULL,
  14. created_at INTEGER NOT NULL,
  15. updated_at INTEGER NOT NULL,
  16. hit_count INTEGER DEFAULT 0,
  17. PRIMARY KEY (date_key, cache_key)
  18. )""",
  19. )
  20. def get_cache(db_path: str, *, date_key: str, cache_key: str) -> dict[str, Any | None]:
  21. ensure_tables(db_path)
  22. conn = sqlite3.connect(db_path)
  23. try:
  24. cur = conn.cursor()
  25. cur.execute(
  26. "SELECT payload_json FROM daily_papers_cache WHERE date_key=? AND cache_key=?",
  27. (str(date_key), str(cache_key)),
  28. )
  29. row = cur.fetchone()
  30. if not row:
  31. return None
  32. raw = row[0] or ""
  33. try:
  34. data = json.loads(raw)
  35. except Exception:
  36. data = None
  37. try:
  38. cur.execute(
  39. "UPDATE daily_papers_cache SET hit_count=hit_count+1, updated_at=? WHERE date_key=? AND cache_key=?",
  40. (int(time.time()), str(date_key), str(cache_key)),
  41. )
  42. conn.commit()
  43. except Exception:
  44. pass
  45. return data if isinstance(data, dict) else None
  46. finally:
  47. conn.close()
  48. def set_cache(db_path: str, *, date_key: str, cache_key: str, payload: dict[str, Any]) -> None:
  49. ensure_tables(db_path)
  50. now = int(time.time())
  51. conn = sqlite3.connect(db_path)
  52. try:
  53. cur = conn.cursor()
  54. cur.execute(
  55. """
  56. INSERT INTO daily_papers_cache(date_key, cache_key, payload_json, created_at, updated_at, hit_count)
  57. VALUES(?,?,?,?,?,?)
  58. ON CONFLICT(date_key, cache_key) DO UPDATE SET
  59. payload_json=excluded.payload_json,
  60. updated_at=excluded.updated_at
  61. """,
  62. (str(date_key), str(cache_key), json.dumps(payload, ensure_ascii=False), now, now, 0),
  63. )
  64. conn.commit()
  65. finally:
  66. conn.close()