bristol-eurostar/cache.py
Edward Betts cd37f0619b Add config system with TFL_DATA_DIR and CACHE_DIR
config/default.py holds defaults using ~/lib/data/tfl (expanduser, so safe
to commit). app.py loads it then overlays config/local.py if present, pushing
paths into cache and circle_line modules. config/local.py is gitignored for
machine-specific absolute paths (e.g. on the server where www-data runs).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 13:37:44 +01:00

27 lines
777 B
Python

import json
import os
import time
from config.default import CACHE_DIR # overridden by app config after import
def _cache_path(key: str) -> str:
safe_key = key.replace('/', '_').replace(' ', '_')
return os.path.join(CACHE_DIR, f"{safe_key}.json")
def get_cached(key: str, ttl: int | None = None):
"""Return cached data, or None if missing or older than ttl seconds."""
path = _cache_path(key)
if not os.path.exists(path):
return None
if ttl is not None and time.time() - os.path.getmtime(path) > ttl:
return None
with open(path) as f:
return json.load(f)
def set_cached(key: str, data) -> None:
os.makedirs(CACHE_DIR, exist_ok=True)
with open(_cache_path(key), 'w') as f:
json.dump(data, f, indent=2)