Skip to content

Commit

Permalink
Add json dump and load opts
Browse files Browse the repository at this point in the history
  • Loading branch information
gergesh committed Dec 23, 2024
1 parent 68b24d6 commit 1da8499
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions pickledb.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,25 @@
from threading import Thread


def load(location, auto_dump, sig=True):
def load(location, auto_dump, sig=True, dump_opts=None, load_opts=None):
'''Return a pickledb object. location is the path to the json file.'''
return PickleDB(location, auto_dump, sig)
return PickleDB(location, auto_dump, sig, dump_opts or {}, load_opts or {})


class PickleDB(object):

key_string_error = TypeError('Key/name must be a string!')

def __init__(self, location, auto_dump, sig):
def __init__(self, location, auto_dump, sig, dump_opts, load_opts):
'''Creates a database object and loads the data from the location path.
If the file does not exist it will be created on the first update.
'''
self.load(location, auto_dump)
self.dthread = None
if sig:
self.set_sigterm_handler()
self.dump_opts = dump_opts
self.load_opts = load_opts

def __getitem__(self, item):
'''Syntax sugar for get()'''
Expand Down Expand Up @@ -92,7 +94,7 @@ def load(self, location, auto_dump):
def _dump(self):
'''Dump to a temporary file, and then move to the actual location'''
with NamedTemporaryFile(mode='wt', delete=False) as f:
json.dump(self.db, f)
json.dump(self.db, f, **self.dump_opts)
if os.stat(f.name).st_size != 0:
shutil.move(f.name, self.loco)

Expand All @@ -106,7 +108,7 @@ def dump(self):
def _loaddb(self):
'''Load or reload the json info from the file'''
try:
self.db = json.load(open(self.loco, 'rt'))
self.db = json.load(open(self.loco, 'rt'), **self.load_opts)
except ValueError:
if os.stat(self.loco).st_size == 0: # Error raised because file is empty
self.db = {}
Expand Down

0 comments on commit 1da8499

Please sign in to comment.