Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple "database" class in Python -- basically a dict which can load-from/write-to disk without you manually calling json.load()/json.dump()
import json
class DataBase(object):
def __init__(self, path):
self.path = path
self.load()
def load(self):
try:
with open(self.path) as f:
try:
self.db = json.load(f)
except json.decoder.JSONDecodeError:
if not f.read(): # file is empty
self.db = {}
self.write()
else:
raise
except FileNotFoundError:
with open(self.path, 'w') as f:
f.write('{}')
self.db = {}
self.clear = self.db.clear
self.copy = self.db.copy
self.items = self.db.items
self.keys = self.db.keys
self.values = self.db.values
def write(self):
with open(self.path, 'w') as f:
json.dump(self.db, f, ensure_ascii=False)
def __getitem__(self, key):
return self.db[key]
def __setitem__(self, key, item):
self.db[key] = item
def __len__(self):
return len(self.db)
def __delitem__(self, key):
del self.db[key]
def __iter__(self):
return iter(self.db)
def pop(self, *args):
return self.db.pop(*args)
def has_key(self, key):
return key in self.db
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.