use postgresql as cache solution
A interesting solution generated by llm codestral
.
import psycopg2
import json
class Cache:
def __init__(self, dbname, user, password, host, port):
self.conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT, expires_at TIMESTAMPTZ)")
def get(self, key):
self.cur.execute("SELECT value FROM cache WHERE key = %s AND expires_at > NOW()", (key,))
result = self.cur.fetchone()
if result:
return result[0]
return None
def setx(self, key, value, expires_in=604800):
self.cur.execute("INSERT INTO cache (key, value, expires_at) VALUES (%s, %s, NOW() + INTERVAL '%s seconds') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at", (key, value, expires_in))
self.conn.commit()
The good part is upsert
is used to reuse existing record (and avoid delete it first).