"""磁盘缓存: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, ttl_seconds: int = 0): """写入缓存,过期时间 = now + ttl_hours + ttl_seconds(支持秒级短 TTL)""" expires_at = (datetime.now() + timedelta(hours=ttl_hours, seconds=ttl_seconds)).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() def clear_all(): """清空全部缓存(每日开盘后 9:31 调用,保证当日数据全新)""" conn = get_connection() try: conn.execute("DELETE FROM cache") conn.commit() finally: conn.close()