summaryrefslogtreecommitdiff
path: root/django/factwise-python/factwise_submission/plannerapp/storage.py
blob: 324e0c036a729ce661a24a8537bd9278964babfe (plain)
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
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)