File size: 1,448 Bytes
21bdc64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# ๋ถ„์„ ๊ฒฐ๊ณผ๋ฅผ ํ‚ค์›Œ๋“œ+๋‚ ์งœ ๋‹จ์œ„๋กœ ์บ์‹ฑํ•˜๋Š” 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)),
        )