1
0
mirror of https://github.com/craigerl/aprsd.git synced 2025-07-03 01:15:17 -04:00

Be more careful picking data to/from disk

This patch ensures that the pickle file is opened and closed correctly
as well as trapping for any exceptions that might occur while loading
a pickle file.
This commit is contained in:
Hemna 2021-11-02 08:52:02 -04:00
parent d2e8fe660f
commit cefb581bb8

View File

@ -70,7 +70,8 @@ class ObjectStoreMixin:
"""Save any queued to disk?""" """Save any queued to disk?"""
if len(self) > 0: if len(self) > 0:
LOG.info(f"{self.__class__.__name__}::Saving {len(self)} entries to disk at {self._save_location()}") LOG.info(f"{self.__class__.__name__}::Saving {len(self)} entries to disk at {self._save_location()}")
pickle.dump(self._dump(), open(self._save_filename(), "wb+")) with open(self._save_filename(), "wb+") as fp:
pickle.dump(self._dump(), fp)
else: else:
LOG.debug( LOG.debug(
"{} Nothing to save, flushing old save file '{}'".format( "{} Nothing to save, flushing old save file '{}'".format(
@ -82,11 +83,19 @@ class ObjectStoreMixin:
def load(self): def load(self):
if os.path.exists(self._save_filename()): if os.path.exists(self._save_filename()):
raw = pickle.load(open(self._save_filename(), "rb")) try:
if raw: with open(self._save_filename(), "rb") as fp:
self.data = raw raw = pickle.load(fp)
LOG.debug(f"{self.__class__.__name__}::Loaded {len(self)} entries from disk.") if raw:
LOG.debug(f"{self.data}") self.data = raw
LOG.debug(
f"{self.__class__.__name__}::Loaded {len(self)} entries from disk.",
)
LOG.debug(f"{self.data}")
except pickle.UnpicklingError as ex:
LOG.error(f"Failed to UnPickle {self._save_filename()}")
LOG.error(ex)
self.data = {}
def flush(self): def flush(self):
"""Nuke the old pickle file that stored the old results from last aprsd run.""" """Nuke the old pickle file that stored the old results from last aprsd run."""