1
Fork 0
mirror of https://github.com/RGBCube/JsonWrapper synced 2025-09-14 03:37:56 +00:00

Create db.py

This commit is contained in:
RGBCube 2022-01-05 15:15:30 +03:00 committed by GitHub
parent a7037a9cf3
commit e25f89a7e6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

43
db.py Normal file
View file

@ -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)