|
| 1 | +import json |
| 2 | +from hashlib import sha256 |
| 3 | + |
| 4 | +__all__ = ['SqliteCacheStorage'] |
| 5 | + |
| 6 | + |
| 7 | +class SqliteCacheStorage: |
| 8 | + """SQLite cache storage using sqlite3.""" |
| 9 | + |
| 10 | + def __init__(self, db_path: str = 'cache.db', table_name: str = "botasaurus_cache"): |
| 11 | + self.db_path = db_path |
| 12 | + self.table_name = table_name |
| 13 | + self._ensure_table() |
| 14 | + |
| 15 | + def _get_connection(self): |
| 16 | + import sqlite3 |
| 17 | + conn = sqlite3.connect(self.db_path) |
| 18 | + conn.row_factory = sqlite3.Row |
| 19 | + return conn |
| 20 | + |
| 21 | + def _hash(self, data) -> str: |
| 22 | + """Generate sha256 hash from data.""" |
| 23 | + serialized = json.dumps(data).encode('utf-8') |
| 24 | + return sha256(serialized).hexdigest() |
| 25 | + |
| 26 | + def _make_key(self, func_name: str, key_data) -> str: |
| 27 | + """Create cache key from func_name and key_data.""" |
| 28 | + return self._hash([func_name, key_data]) |
| 29 | + |
| 30 | + def _ensure_table(self): |
| 31 | + """Create cache table if not exists.""" |
| 32 | + with self._get_connection() as conn: |
| 33 | + conn.execute(""" |
| 34 | + CREATE TABLE IF NOT EXISTS %s ( |
| 35 | + key CHAR(64) PRIMARY KEY, |
| 36 | + data TEXT, |
| 37 | + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP |
| 38 | + ) |
| 39 | + """ % self.table_name) |
| 40 | + conn.commit() |
| 41 | + |
| 42 | + def get(self, func_name: str, key_data, expires_in=None): |
| 43 | + """ |
| 44 | + Returns: |
| 45 | + {"data": value} if cache hit (value can be None) |
| 46 | + None if cache miss or expired |
| 47 | + """ |
| 48 | + key = self._make_key(func_name, key_data) |
| 49 | + with self._get_connection() as conn: |
| 50 | + cursor = conn.cursor() |
| 51 | + if expires_in is not None: |
| 52 | + cursor.execute( |
| 53 | + f"""SELECT data FROM {self.table_name} |
| 54 | + WHERE key = ? AND created_at > datetime('now', ?)""", |
| 55 | + (key, f'-{int(expires_in.total_seconds())} seconds') |
| 56 | + ) |
| 57 | + row = cursor.fetchone() |
| 58 | + if row is None: |
| 59 | + cursor.execute( |
| 60 | + "DELETE FROM %s WHERE key = ?" % self.table_name, |
| 61 | + (key,) |
| 62 | + ) |
| 63 | + conn.commit() |
| 64 | + return None |
| 65 | + else: |
| 66 | + cursor.execute( |
| 67 | + "SELECT data FROM %s WHERE key = ?" % self.table_name, |
| 68 | + (key,) |
| 69 | + ) |
| 70 | + row = cursor.fetchone() |
| 71 | + |
| 72 | + if row: |
| 73 | + return {"data": json.loads(row["data"])} |
| 74 | + return None |
| 75 | + |
| 76 | + def put(self, func_name: str, key_data, data) -> None: |
| 77 | + key = self._make_key(func_name, key_data) |
| 78 | + data_json = json.dumps(data) |
| 79 | + with self._get_connection() as conn: |
| 80 | + conn.execute(""" |
| 81 | + INSERT INTO %s (key, data, created_at) |
| 82 | + VALUES (?, ?, CURRENT_TIMESTAMP) |
| 83 | + ON CONFLICT (key) DO UPDATE SET |
| 84 | + data = excluded.data, |
| 85 | + created_at = CURRENT_TIMESTAMP |
| 86 | + """ % self.table_name, (key, data_json)) |
| 87 | + conn.commit() |
| 88 | + |
| 89 | + def delete(self, func_name: str, key_data) -> None: |
| 90 | + key = self._make_key(func_name, key_data) |
| 91 | + with self._get_connection() as conn: |
| 92 | + conn.execute( |
| 93 | + "DELETE FROM %s WHERE key = ?" % self.table_name, |
| 94 | + (key,) |
| 95 | + ) |
| 96 | + conn.commit() |
| 97 | + |
| 98 | + |
0 commit comments