59 lines
1.5 KiB
Python
59 lines
1.5 KiB
Python
"""磁盘缓存:SQLite 持久化,重启不丢"""
|
|
|
|
import json
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional
|
|
|
|
from database import get_connection
|
|
|
|
|
|
def get_cache(key: str) -> Optional[str]:
|
|
"""获取缓存,过期或不存在返回 None"""
|
|
now = datetime.now().isoformat()
|
|
conn = get_connection()
|
|
try:
|
|
row = conn.execute(
|
|
"SELECT value FROM cache WHERE key = ? AND expires_at > ?",
|
|
(key, now),
|
|
).fetchone()
|
|
if row:
|
|
return row["value"]
|
|
return None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def set_cache(key: str, value: str, ttl_hours: int = 6):
|
|
"""写入缓存,过期时间 = now + ttl_hours"""
|
|
expires_at = (datetime.now() + timedelta(hours=ttl_hours)).isoformat()
|
|
conn = get_connection()
|
|
try:
|
|
conn.execute(
|
|
"INSERT OR REPLACE INTO cache (key, value, expires_at) VALUES (?, ?, ?)",
|
|
(key, value, expires_at),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def del_cache(key: str):
|
|
"""删除指定缓存"""
|
|
conn = get_connection()
|
|
try:
|
|
conn.execute("DELETE FROM cache WHERE key = ?", (key,))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def clean_expired():
|
|
"""清理已过期的缓存(可在启动时调用一次)"""
|
|
now = datetime.now().isoformat()
|
|
conn = get_connection()
|
|
try:
|
|
conn.execute("DELETE FROM cache WHERE expires_at <= ?", (now,))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|