File size: 1,429 Bytes
1e34d32 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | from __future__ import annotations
import json
from pathlib import Path
from backend.models import SpaceItem
ROOT_DIR = Path(__file__).resolve().parents[1]
DATA_DIR = ROOT_DIR / "data"
def _ensure_parent(path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
def load_spaces_cache(path: str = "data/spaces_cache.json") -> list[SpaceItem]:
cache_path = Path(path)
if not cache_path.exists():
return []
try:
payload = json.loads(cache_path.read_text(encoding="utf-8"))
except Exception:
return []
if not isinstance(payload, list):
return []
return [SpaceItem.from_dict(item) for item in payload if isinstance(item, dict)]
def save_spaces_cache(spaces: list[SpaceItem], path: str = "data/spaces_cache.json") -> None:
cache_path = Path(path)
_ensure_parent(cache_path)
cache_path.write_text(
json.dumps([space.to_dict() for space in spaces], indent=2, ensure_ascii=False),
encoding="utf-8",
)
def load_sample_spaces(path: str = "data/sample_spaces.json") -> list[SpaceItem]:
sample_path = Path(path)
if not sample_path.exists():
return []
try:
payload = json.loads(sample_path.read_text(encoding="utf-8"))
except Exception:
return []
if not isinstance(payload, list):
return []
return [SpaceItem.from_dict(item) for item in payload if isinstance(item, dict)]
|