From e25f89a7e640207d0c0a161cee66de0702cc9f30 Mon Sep 17 00:00:00 2001 From: RGBCube <78925721+RGBCube@users.noreply.github.com> Date: Wed, 5 Jan 2022 15:15:30 +0300 Subject: [PATCH] Create db.py --- db.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 db.py diff --git a/db.py b/db.py new file mode 100644 index 0000000..6091544 --- /dev/null +++ b/db.py @@ -0,0 +1,43 @@ +import json +import os + + +class ClutterDB: + + def __init__(self, path_to_json: str): + self.path_to_json = path_to_json + if not os.path.isfile(path_to_json): + with open(path_to_json, "w") as json_file: + json.dump({}, json_file) + else: + if os.path.getsize(path_to_json) == 0: + with open(path_to_json, "w") as json_file: + json.dump({}, json_file) + + def set(self, key: str, value): + with open(self.path_to_json, mode="r") as json_file: + json_data = json.load(json_file) + with open(self.path_to_json, mode="w") as json_file: + json_data[key] = value + json.dump(json_data, json_file) + + def get(self, key: str, **kwargs): + with open(self.path_to_json, mode="r") as json_file: + json_data = json.load(json_file) + if key in json_data: + return json_data[key] + elif "default" in kwargs: + return kwargs["default"] + else: + return None + + def rem(self, key: str): + with open(self.path_to_json, mode="r") as json_file: + json_data = json.load(json_file) + with open(self.path_to_json, mode="w") as json_file: + json_data.pop(key, None) + json.dump(json_data, json_file) + + def nuke(self): + with open(self.path_to_json, mode="w") as json_file: + json.dump({}, json_file)