prevent file corruption during json.dump

This commit is contained in:
Jakob Ketterl 2021-02-16 17:17:09 +01:00
parent 496e771e17
commit 3c0a26eaa8
3 changed files with 9 additions and 3 deletions

View File

@ -93,8 +93,10 @@ class Bookmarks(object):
return "{data_directory}/bookmarks.json".format(data_directory=coreConfig.get_data_directory())
def store(self):
# don't write directly to file to avoid corruption on exceptions
jsonContent = json.dumps([b.__dict__() for b in self.bookmarks], indent=4)
with open(Bookmarks._getBookmarksFile(), "w") as file:
json.dump([b.__dict__() for b in self.bookmarks], file, indent=4)
file.write(jsonContent)
self.file_modified = self._getFileModifiedTimestamp()
def addBookmark(self, bookmark: Bookmark):

View File

@ -21,5 +21,7 @@ class DynamicConfig(PropertyLayer):
return "{data_directory}/settings.json".format(data_directory=coreConfig.get_data_directory())
def store(self):
# don't write directly to file to avoid corruption on exceptions
jsonContent = json.dumps(self.__dict__(), indent=4)
with open(DynamicConfig._getSettingsFile(), "w") as file:
json.dump(self.__dict__(), file, indent=4)
file.write(jsonContent)

View File

@ -185,8 +185,10 @@ class UserList(object):
usersFile = self._getUsersFile()
users = [u.toJson() for u in self.values()]
try:
# don't write directly to file to avoid corruption on exceptions
jsonContent = json.dumps(users, indent=4)
with open(usersFile, "w") as f:
json.dump(users, f, indent=4)
f.write(jsonContent)
except Exception:
logger.exception("error while writing users file %s", usersFile)
self.refresh()