From 9041ad7daa7fafdc88900d83e3fec9b7d1dd9ff3 Mon Sep 17 00:00:00 2001 From: avollkopf <43980694+avollkopf@users.noreply.github.com> Date: Sat, 8 Apr 2023 11:55:49 +0200 Subject: [PATCH] added error handling in case of corrupt json config files. --- cbpi/__init__.py | 2 +- cbpi/controller/basic_controller2.py | 42 ++++++++++++++++++++-------- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/cbpi/__init__.py b/cbpi/__init__.py index 7fcced5..8d7482d 100644 --- a/cbpi/__init__.py +++ b/cbpi/__init__.py @@ -1,3 +1,3 @@ -__version__ = "4.1.8.a7" +__version__ = "4.1.8.a8" __codename__ = "Groundhog Day" diff --git a/cbpi/controller/basic_controller2.py b/cbpi/controller/basic_controller2.py index 7ef8b4f..6a4a64f 100644 --- a/cbpi/controller/basic_controller2.py +++ b/cbpi/controller/basic_controller2.py @@ -34,19 +34,39 @@ class BasicController: return self.resource(data.get("id"), data.get("name"), type=data.get("type"), props=Props(data.get("props", {})) ) async def load(self): - logging.info("{} Load ".format(self.name)) - with open(self.path) as json_file: - data = json.load(json_file) - data['data'].sort(key=lambda x: x.get('name').upper()) + try: + logging.info("{} Load ".format(self.name)) + with open(self.path) as json_file: + data = json.load(json_file) + data['data'].sort(key=lambda x: x.get('name').upper()) - for i in data["data"]: - self.data.append(self.create(i)) + for i in data["data"]: + self.data.append(self.create(i)) - if self.autostart is True: - for item in self.data: - logging.info("{} Starting ".format(self.name)) - await self.start(item.id) - await self.push_udpate() + if self.autostart is True: + for item in self.data: + logging.info("{} Starting ".format(self.name)) + await self.start(item.id) + await self.push_udpate() + except Exception as e: + logging.warning("Invalid {} file - Creating empty file".format(self.path)) + os.remove(self.path) + with open(self.path, "w") as file: + json.dump(dict( data=[]), file, indent=4, sort_keys=True) + + with open(self.path) as json_file: + data = json.load(json_file) + data['data'].sort(key=lambda x: x.get('name').upper()) + + for i in data["data"]: + self.data.append(self.create(i)) + + if self.autostart is True: + for item in self.data: + logging.info("{} Starting ".format(self.name)) + await self.start(item.id) + await self.push_udpate() + async def save(self): logging.info("{} Save ".format(self.name))