Spaces:
Runtime error
Runtime error
Update app/cache.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from __future__ import annotationsimport asyncioimport jsonimport loggingfrom collections import dequefrom pathlib import Pathfrom typing import Dequefrom .models import Measurementlogger = logging.getLogger(__name__)class MeasurementCache:def __init__(self, *, maxlen: int = 48, storage_path: Path | str = "data/cache.json") -> None:self._buffer: Deque[Measurement] = deque(maxlen=maxlen)self._lock = asyncio.Lock()self._path = Path(storage_path)self._path.parent.mkdir(parents=True, exist_ok=True)self._load_from_disk()def _load_from_disk(self) -> None:if not self._path.exists():returntry:raw = json.loads(self._path.read_text("utf-8"))except json.JSONDecodeError as exc:logger.warning("Failed to read cache file %s: %s", self._path, exc)returnif not isinstance(raw, list):logger.warning("Invalid cache file format: expected list, got %s", type(raw))returnfor item in raw[-self._buffer.maxlen :]:try:measurement = Measurement.model_validate(item)except Exception as exc: # noqa: BLE001logger.debug("Skipping invalid cache entry %s: %s", item, exc)continueself._buffer.append(measurement)logger.info("Loaded %s cached measurements", len(self._buffer))def _dump_to_disk(self) -> None:data = [m.model_dump(mode="json") for m in self._buffer]tmp_path = self._path.with_suffix(".tmp")tmp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")tmp_path.replace(self._path)async def add(self, measurement: Measurement, *, persist: bool = True) -> None:async with self._lock:latest = self._buffer[-1] if self._buffer else Noneif latest and latest.timestamp == measurement.timestamp:self._buffer.pop()self._buffer.append(measurement)if persist:await asyncio.to_thread(self._dump_to_disk)async def get_latest(self) -> Measurement | None:async with self._lock:return self._buffer[-1] if self._buffer else Noneasync def get_history(self) -> list[Measurement]:async with self._lock:return list(self._buffer)def __len__(self) -> int:return len(self._buffer)12345678910111213141516171819202122232425262728293031323334353637# app/app/cache.pyfrom pathlib import Pathimport os, json, tempfile, osimport asyncioclass Cache:def __init__(self, filename: str = "cache.json"):# bevorzugt /data (persistenter Storage auf HF), sonst /tmpbase = Path(os.getenv("APP_CACHE_DIR", "/data"))if not os.access(base, os.W_OK):base = Path("/tmp/app-cache")base.mkdir(parents=True, exist_ok=True)self.path = base / filenamedef _dump_to_disk(self, data: dict | list | None = None):# vorhandenen Zustand laden/ersetzenif data is None and self.path.exists():try:data = json.loads(self.path.read_text(encoding="utf-8"))except Exception:data = Nonedata = data if data is not None else {}# atomar schreibenwith tempfile.NamedTemporaryFile("w", delete=False, dir=self.path.parent, suffix=".tmp", encoding="utf-8") as tmp:json.dump(data, tmp, ensure_ascii=False, indent=2)tmp_name = tmp.nameos.replace(tmp_name, self.path) # atomarasync def add(self, measurement: dict):# ... füge measurement in deinen Speicher ein ...# Beispiel (anpassen, falls du eine Liste etc. führst):data = {"last": measurement}await asyncio.to_thread(self._dump_to_disk, data)
app/cache.py+37-72