import json import os from filelock import FileLock DB_DIR = os.path.join(os.path.dirname(__file__), '..', 'db') os.makedirs(DB_DIR, exist_ok=True) class FileStorage: def __init__(self, filename): self.path = os.path.join(DB_DIR, filename) self.lock = FileLock(self.path + ".lock") def _ensure(self): if not os.path.exists(self.path): with open(self.path, "w") as f: json.dump([], f) def read_all(self): self._ensure() with self.lock: with open(self.path, "r") as f: return json.load(f) def write_all(self, data): with self.lock: with open(self.path, "w") as f: json.dump(data, f, indent=2) def append(self, item): data = self.read_all() data.append(item) self.write_all(data) def replace(self, data): self.write_all(data)