SQLite-backed cache for local development.
| 75 | del self.expiry[key] |
| 76 | |
| 77 | class SQLiteCache(BaseDevCache): |
| 78 | """SQLite-backed cache for local development.""" |
| 79 | |
| 80 | def __init__(self): |
| 81 | self.db_path = os.path.join(os.getcwd(), "cache.db") |
| 82 | self.conn = sqlite3.connect(self.db_path) |
| 83 | self.conn.execute(""" |
| 84 | CREATE TABLE IF NOT EXISTS cache ( |
| 85 | key TEXT PRIMARY KEY, |
| 86 | value TEXT, |
| 87 | expiry INTEGER |
| 88 | ) |
| 89 | """) |
| 90 | self.conn.commit() |
| 91 | |
| 92 | def get(self, key: str) -> str | None: |
| 93 | cursor = self.conn.execute("SELECT value, expiry FROM cache WHERE key = ?", (key,)) |
| 94 | row = cursor.fetchone() |
| 95 | if row: |
| 96 | value, expiry = row |
| 97 | if expiry is not None and time.time() > expiry: |
| 98 | self.delete(key) |
| 99 | return None |
| 100 | return value |
| 101 | return None |
| 102 | |
| 103 | def setex(self, key: str, expiry: int, value: str) -> None: |
| 104 | expiry_time = int(time.time() + expiry) |
| 105 | self.conn.execute( |
| 106 | """ |
| 107 | INSERT OR REPLACE INTO cache (key, value, expiry) |
| 108 | VALUES (?, ?, ?) |
| 109 | """, |
| 110 | (key, value, expiry_time), |
| 111 | ) |
| 112 | self.conn.commit() |
| 113 | |
| 114 | def expire(self, key: str, expiry: int) -> None: |
| 115 | expiry_time = int(time.time() + expiry) |
| 116 | self.conn.execute( |
| 117 | """ |
| 118 | UPDATE cache SET expiry = ? WHERE key = ? |
| 119 | """, |
| 120 | (expiry_time, key), |
| 121 | ) |
| 122 | self.conn.commit() |
| 123 | |
| 124 | def delete(self, key: str) -> None: |
| 125 | self.conn.execute("DELETE FROM cache WHERE key = ?", (key,)) |
| 126 | self.conn.commit() |
| 127 | |
| 128 | if os.path.exists("/.dockerenv"): |
| 129 | logger.info("Using in-memory cache for local development.") |
no outgoing calls
no test coverage detected
searching dependent graphs…