# 분석 결과를 키워드+날짜 단위로 캐싱하는 SQLite 래퍼 (재조회 시 즉시 반환) import os import json import sqlite3 from datetime import date DB_PATH = os.path.join(os.path.dirname(__file__), "cache.db") def _conn(): return sqlite3.connect(DB_PATH) def init(): # 캐시 테이블 생성 (없으면) with _conn() as c: c.execute( """ create table if not exists analysis_cache ( keyword text not null, collected_date text not null, payload text not null, primary key (keyword, collected_date) ) """ ) def get(keyword: str, day: str | None = None) -> dict | None: # 같은 날짜의 캐시가 있으면 반환, 없으면 None day = day or date.today().isoformat() with _conn() as c: row = c.execute( "select payload from analysis_cache where keyword=? and collected_date=?", (keyword, day), ).fetchone() return json.loads(row[0]) if row else None def put(keyword: str, payload: dict, day: str | None = None): # 분석 결과 저장 (같은 키워드+날짜는 덮어씀) day = day or date.today().isoformat() with _conn() as c: c.execute( "insert or replace into analysis_cache values (?, ?, ?)", (keyword, day, json.dumps(payload, ensure_ascii=False)), )