Handle exceptions when loading extensions

This commit is contained in:
Joel Collins 2020-01-14 16:36:24 +00:00
parent fc6bea3359
commit 5f11994be5

View file

@ -1,6 +1,7 @@
import logging
import collections
import copy
import traceback
from importlib import util
import sys
@ -20,6 +21,7 @@ class BaseExtension:
Handles binding route views and forms.
"""
# TODO: Allow adding components to extensions
def __init__(self, name: str, description="", version="0.0.0"):
@ -113,19 +115,25 @@ def find_instances_in_module(module, class_to_find):
return objs
def find_extensions_in_file(extension_path: str, module_name="extensions"):
def find_extensions_in_file(extension_path: str, module_name="extensions") -> list:
logging.debug(f"Loading extensions from {extension_path}")
spec = util.spec_from_file_location(module_name, extension_path)
mod = util.module_from_spec(spec)
sys.modules[spec.name] = mod
spec.loader.exec_module(mod)
if hasattr(mod, "__extensions__"):
return [getattr(mod, ext_name) for ext_name in mod.__extensions__]
try:
spec.loader.exec_module(mod)
except Exception as e:
logging.error(
f"Exception in extension path {extension_path}: \n{traceback.format_exc()}"
)
return []
else:
return find_instances_in_module(mod, BaseExtension)
if hasattr(mod, "__extensions__"):
return [getattr(mod, ext_name) for ext_name in mod.__extensions__]
else:
return find_instances_in_module(mod, BaseExtension)
def find_extensions(extension_dir: str, module_name="extensions"):