diff options
Diffstat (limited to 'django/factwise-python/factwise_submission/plannerapp/storage.py')
| -rw-r--r-- | django/factwise-python/factwise_submission/plannerapp/storage.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/django/factwise-python/factwise_submission/plannerapp/storage.py b/django/factwise-python/factwise_submission/plannerapp/storage.py new file mode 100644 index 0000000..324e0c0 --- /dev/null +++ b/django/factwise-python/factwise_submission/plannerapp/storage.py @@ -0,0 +1,36 @@ +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) + |
