Skip to content

Instantly share code, notes, and snippets.

@bharadwaj-raju
Last active January 6, 2018 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bharadwaj-raju/0d594deb3e38ce6859ffd21cedc59fd8 to your computer and use it in GitHub Desktop.
Save bharadwaj-raju/0d594deb3e38ce6859ffd21cedc59fd8 to your computer and use it in GitHub Desktop.
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