From 1da8499aa2a800821a644423893419df5f8dad33 Mon Sep 17 00:00:00 2001 From: Yoav Shai Date: Mon, 23 Dec 2024 11:56:56 +0200 Subject: [PATCH] Add json dump and load opts --- pickledb.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/pickledb.py b/pickledb.py index 8ff5552..1d1ff08 100644 --- a/pickledb.py +++ b/pickledb.py @@ -40,16 +40,16 @@ 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. ''' @@ -57,6 +57,8 @@ def __init__(self, location, auto_dump, sig): 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()''' @@ -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) @@ -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 = {}