-
Notifications
You must be signed in to change notification settings - Fork 1
/
json_db.py
40 lines (31 loc) · 1.09 KB
/
json_db.py
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
import json
import pathlib
import contextlib
from typing import Any
class JSON_DB:
def __init__(self, project_path: str):
self.db_path = pathlib.Path(project_path).parent / "db.json"
self.data = self._load_data()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.save()
print("I've saved the database successfully")
def save(self):
with open(self.db_path, "w") as json_file:
json.dump(self.data, json_file)
def set(self, field: str, value: Any):
self.data[field] = value
def get(self, field: str, *, default: Any = None) -> Any:
return self.data.get(field, default)
def has(self, field: str) -> bool:
return field in self.data
def _load_data(self) -> dict[str, Any]:
with contextlib.ExitStack() as stack:
try:
json_file = open(self.db_path)
except FileNotFoundError:
return {}
else:
stack.enter_context(json_file)
return json.load(json_file)