Cache provisional weekday timetables
This commit is contained in:
parent
378d2484d0
commit
bc7cb9cffa
6 changed files with 686 additions and 58 deletions
19
cache.py
19
cache.py
|
|
@ -1,6 +1,7 @@
|
|||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from config.default import CACHE_DIR # overridden by app config after import
|
||||
|
||||
|
|
@ -13,15 +14,21 @@ def _cache_path(key: str) -> str:
|
|||
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):
|
||||
try:
|
||||
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)
|
||||
except (OSError, json.JSONDecodeError):
|
||||
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:
|
||||
path = _cache_path(key)
|
||||
tmp_path = f"{path}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
|
||||
with open(tmp_path, 'w') as f:
|
||||
json.dump(data, f, indent=2)
|
||||
os.replace(tmp_path, path)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue