Repository: OpenBB-finance/OpenBBTerminal
File: openbb_platform/extensions/platform_api/openbb_platform_api/utils/api.py (Python)

Code before:
def import_app(app_path: str, name: str = "app", factory: bool = False):
    """Import the FastAPI app instance from a local file."""
    # pylint: disable=import-outside-toplevel
    from fastapi import FastAPI  # noqa
    from fastapi.middleware.cors import CORSMiddleware
    from importlib import util
    from openbb_core.api.app_loader import AppLoader
    from openbb_core.api.rest_api import system

    if not str(app_path).startswith("/"):
        cwd = Path.cwd()
        app_path = str(cwd.joinpath(app_path).resolve())

    if not Path(app_path).exists():
        raise FileNotFoundError(f"Error: The app file '{app_path}' does not exist")

    spec_name = os.path.basename(app_path).split(".")[0]
    spec = util.spec_from_file_location(spec_name, app_path)

    if spec is None:
        raise RuntimeError(f"Failed to load the file specs for '{app_path}'")

    module = util.module_from_spec(spec)  # type: ignore
    sys.modules[spec_name] = module  # type: ignore
    spec.loader.exec_module(module)  # type: ignore

    if not hasattr(module, name):
        raise AttributeError(
            f"Error: The app file '{app_path}' does not contain an '{name}' instance"
        )

    if (
        hasattr(module, name)
        and not isinstance(getattr(module, name), FastAPI)
        and factory is False
    ):
        print(  # noqa: T201
            "\n\n[WARNING]   App factory detected. Using it, but please consider setting the --factory flag explicitly.\n"
        )
        factory = True

    if factory:
        factory_func = getattr(module, name)
        return_annotation = getattr(factory_func, "__annotations__", {}).get("return")

        if not return_annotation or return_annotation is not FastAPI:
            raise TypeError(
                f"Factory function must return an instance of FastAPI, got {return_annotation} instead."
            )

        app = factory_func()

Review comment (suggestion):
This should expand to other base error messages that might trigger, for example, `ModuleNotFoundError`

<img width="759" alt="Screenshot 2025-03-12 at 8 45 49 PM" src="https://github.com/user-attachments/assets/5416eefd-b9d4-44b6-8547-7a39f577c010" />


Code after:
    """Import the FastAPI app instance from a local file or module."""
    # pylint: disable=import-outside-toplevel
    from fastapi import FastAPI  # noqa
    from fastapi.middleware.cors import CORSMiddleware
    from importlib import import_module, util
    from openbb_core.api.app_loader import AppLoader
    from openbb_core.api.rest_api import system

    def _load_module_from_file_path(file_path: str):
        spec_name = os.path.basename(file_path).split(".")[0]
        spec = util.spec_from_file_location(spec_name, file_path)

        if spec is None:
            raise RuntimeError(f"Failed to load the file specs for '{file_path}'")

        module = util.module_from_spec(spec)  # type: ignore
        sys.modules[spec_name] = module  # type: ignore
        spec.loader.exec_module(module)  # type: ignore
        return module

    # Case 1: Module path with colon notation (e.g., "my_app.main:app" or "main:app")
    if ":" in app_path:
        module_path, name = app_path.split(":")
        try:  # First try to import as a module
            module = import_module(module_path)
        except ImportError:  # If module import fails, try to load as a local file
            if not module_path.endswith(".py"):
                module_path += ".py"

            if not str(module_path).startswith("/"):
                cwd = Path.cwd()
                file_path = str(cwd.joinpath(module_path).resolve())
            else:
                file_path = module_path

            if not Path(file_path).exists():
                raise FileNotFoundError(  # pylint: disable=raise-missing-from
                    f"Error: Neither module '{module_path}' could be imported nor file '{file_path}' exists"
                )

            module = _load_module_from_file_path(file_path)

    # Case 2: File path (e.g., "main.py" or "my_app/main.py")
    else:
        if not str(app_path).startswith("/"):
            cwd = Path.cwd()
            app_path = str(cwd.joinpath(app_path).resolve())

        if not Path(app_path).exists():
            raise FileNotFoundError(f"Error: The app file '{app_path}' does not exist")