summaryrefslogtreecommitdiff
path: root/new/lib/objectstorage.py
blob: 834fb57def157e9a5e8c7b7da220b0f7c1a64c06 (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import json
from json import JSONDecodeError
import os


class ObjectStorage:
    _data = None
    _loaded = False

    def __init__(self, path, root_type, fallback):
        self.path = path
        self.root_type = root_type
        self.fallback = fallback

    def get(self, name, default=None, data_type=None, bypass_cache=False):
        data = self.load(bypass_cache)
        if name in data:
            value = data[name]
            if data_type is not None:
                try:
                    return data_type(value)
                except (TypeError, ValueError):
                    pass
            else:
                return value
        return default

    def set(self, name, value, flush=True, bypass_cache=False):
        data = self.load(bypass_cache)
        data[name] = value
        if flush:
            self.save(data)

    def callback(self, name, callback):
        data = self.load()
        if data and name in data:
            return data[name]

        data[name] = callback()
        self.save(data)
        return data[name]

    def load(self, bypass_cache=False):
        if not self._loaded or bypass_cache:
            if os.path.exists(self.path):
                with open(self.path, "r") as file:
                    try:
                        contents = json.load(file)
                        self._data = self.root_type(contents)
                        self._loaded = True
                    except (JSONDecodeError, TypeError, ValueError):
                        pass

            if not self._loaded:
                self._loaded = True
                self._data = self.fallback

        return self._data

    def flush(self):
        self.save(self.load())

    def save(self, contents):
        directory = os.path.dirname(self.path)
        if directory and not os.path.exists(directory):
            os.makedirs(directory)

        with open(self.path, "w") as file:
            json.dump(contents, file, indent=True)

    def purge(self):
        if os.path.exists(self.path):
            os.remove(self.path)

    def clear_cache(self):
        self._loaded = False
        self._data = None