74 lines
2.3 KiB
Python
74 lines
2.3 KiB
Python
"""Cache management with TTL support."""
|
|
|
|
import json
|
|
import time
|
|
import logging
|
|
from typing import Dict, Any, Optional
|
|
import config
|
|
|
|
logger = logging.getLogger("syllabus")
|
|
|
|
|
|
class CacheManager:
|
|
"""Manage application cache with TTL support."""
|
|
|
|
def __init__(self, ttl: int = None):
|
|
"""Initialize cache manager with optional TTL."""
|
|
self.ttl = ttl or config.CACHE_TTL
|
|
self.data: Optional[Dict[str, Any]] = None
|
|
self.timestamp: Optional[float] = None
|
|
|
|
def is_valid(self) -> bool:
|
|
"""Check if cache is still valid."""
|
|
if self.data is None or self.timestamp is None:
|
|
return False
|
|
elapsed = time.time() - self.timestamp
|
|
return elapsed < self.ttl
|
|
|
|
def get(self) -> Optional[Dict[str, Any]]:
|
|
"""Get cached data if valid, None otherwise."""
|
|
if self.is_valid():
|
|
return self.data
|
|
return None
|
|
|
|
def set(self, data: Dict[str, Any]) -> None:
|
|
"""Store data in cache with current timestamp."""
|
|
self.data = data
|
|
self.timestamp = time.time()
|
|
logger.debug(f"Cache updated with {len(data) if isinstance(data, list) else 'data'}")
|
|
|
|
def clear(self) -> None:
|
|
"""Clear the cache."""
|
|
self.data = None
|
|
self.timestamp = None
|
|
logger.debug("Cache cleared")
|
|
|
|
def load_from_file(self, filepath: str) -> Optional[Dict[str, Any]]:
|
|
"""Load data from JSON file and cache it."""
|
|
try:
|
|
with open(filepath, 'r') as f:
|
|
data = json.load(f, object_pairs_hook=dict)
|
|
self.set(data)
|
|
return data
|
|
except (IOError, json.JSONDecodeError) as e:
|
|
logger.error(f"Failed to load cache from {filepath}: {e}")
|
|
return None
|
|
|
|
def save_to_file(self, filepath: str) -> bool:
|
|
"""Save cached data to JSON file."""
|
|
if self.data is None:
|
|
logger.warning("No data to save to cache file")
|
|
return False
|
|
try:
|
|
with open(filepath, 'w') as f:
|
|
json.dump(self.data, f, indent=4)
|
|
logger.debug(f"Cache saved to {filepath}")
|
|
return True
|
|
except IOError as e:
|
|
logger.error(f"Failed to save cache to {filepath}: {e}")
|
|
return False
|
|
|
|
|
|
# Global cache instance
|
|
series_cache = CacheManager()
|