PhotosAPI/modules/extensions_loader.py

59 lines
2.0 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
2023-08-14 14:44:07 +03:00
from typing import Union
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
2023-08-14 14:44:07 +03:00
def dynamic_import(module_name: str, py_path: str):
2022-12-20 02:22:32 +02:00
try:
module_spec = spec_from_file_location(module_name, py_path)
2023-08-14 14:44:07 +03:00
if module_spec is None:
raise RuntimeError(
f"Module spec from module name {module_name} and path {py_path} is None"
)
module = module_from_spec(module_spec)
module_spec.loader.exec_module(module)
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
2023-08-14 14:44:07 +03:00
except Exception as exc:
print(f"Could not load extension {module_name} due to {exc}", flush=True)
2022-12-20 02:22:32 +02:00
return
2023-08-14 14:44:07 +03:00
def dynamic_import_from_src(src: Union[str, Path], 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
# =================================================================================