bristol-eurostar/cache.py
Edward Betts 6b044b9493 Add 24-hour TTL to Eurostar price cache
Cache reads now accept an optional ttl (seconds). get_cached checks the
file mtime and returns None if the entry is older than the TTL, triggering
a fresh fetch. Eurostar prices use a 24-hour TTL; timetable caches remain
indefinite (date-scoped keys become irrelevant once the date passes).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 10:38:47 +01:00

27 lines
760 B
Python

import json
import os
import time
CACHE_DIR = os.path.join(os.path.dirname(__file__), 'cache')
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)