PhotosAPI/modules/extensions_loader.py

54 lines
1.8 KiB
Python
Raw Normal View History

2022-12-20 02:22:32 +02:00
from importlib.util import module_from_spec, spec_from_file_location
from os import getcwd, path, walk
2023-06-23 11:51:42 +03:00
from pathlib import Path
2022-12-20 02:22:32 +02:00
2023-03-12 15:59:13 +02:00
# =================================================================================
2022-12-20 02:22:32 +02:00
# Import functions
# Took from https://stackoverflow.com/a/57892961
def get_py_files(src):
2023-03-12 15:59:13 +02:00
cwd = getcwd() # Current Working directory
py_files = []
2022-12-20 02:22:32 +02:00
for root, dirs, files in walk(src):
2023-06-23 13:17:01 +03:00
py_files.extend(
Path(f"{cwd}/{root}/{file}") for file in files if file.endswith(".py")
)
2022-12-20 02:22:32 +02:00
return py_files
def dynamic_import(module_name, py_path):
try:
module_spec = spec_from_file_location(module_name, py_path)
2023-03-12 15:59:13 +02:00
module = module_from_spec(module_spec) # type: ignore
module_spec.loader.exec_module(module) # type: ignore
2022-12-20 02:22:32 +02:00
return module
except SyntaxError:
2023-03-12 15:59:13 +02:00
print(
f"Could not load extension {module_name} due to invalid syntax. Check logs/errors.log for details.",
flush=True,
)
2022-12-20 02:22:32 +02:00
return
except Exception as exp:
print(f"Could not load extension {module_name} due to {exp}", flush=True)
return
2023-03-12 15:59:13 +02:00
def dynamic_import_from_src(src, star_import=False):
2022-12-20 02:22:32 +02:00
my_py_files = get_py_files(src)
for py_file in my_py_files:
2023-06-23 12:17:02 +03:00
module_name = Path(py_file).stem
2022-12-20 02:22:32 +02:00
print(f"Importing {module_name} extension...", flush=True)
imported_module = dynamic_import(module_name, py_file)
if imported_module != None:
if star_import:
for obj in dir(imported_module):
globals()[obj] = imported_module.__dict__[obj]
else:
globals()[module_name] = imported_module
print(f"Successfully loaded {module_name} extension", flush=True)
return
2023-03-12 15:59:13 +02:00
# =================================================================================