pallets/flask · error · NoAppException

While importing , an ImportError was raised:\n\n

Error message

While importing {module_name!r}, an ImportError was raised:\n\n{traceback.format_exc()}

What it means

locate_app() calls __import__(module_name). If ImportError is raised and sys.exc_info()[2].tb_next exists (traceback depth > 1), the failure happened inside the imported module (a transitive import error), not because the module name itself was unknown. Flask re-raises it as NoAppException embedding the full traceback so you can see which line inside your module failed to import.

Solutions

  1. Read the embedded traceback in the error message to find the exact line and missing name inside your module.
  2. Install the missing dependency or fix the offending import statement.
  3. Ensure you run flask from the correct virtualenv / working directory where all imports resolve.

Example fix

# before: mypkg/__init__.py
from flask_sqlachemy import SQLAlchemy  # typo, raises ImportError

# after
from flask_sqlalchemy import SQLAlchemy
Defensive patterns

Strategy: try-catch

Validate before calling

import importlib

def can_import_clean(module_name: str) -> bool:
    try:
        importlib.import_module(module_name)
        return True
    except ImportError:
        return False

Type guard

null

Try / catch

import importlib
try:
    importlib.import_module(module_name)
except ImportError as e:
    import traceback
    tb = e.__traceback__
    if tb and tb.tb_next:
        print(f'Error inside module body; see traceback:\n{traceback.format_exc()}')
    raise

Prevention

When it happens

Trigger: The target module exists but executing it raises ImportError—e.g. it imports a package that is not installed, has a circular import, references a moved symbol, or has a syntax/attribute error surfacing as ImportError during its own imports. The tb_next presence distinguishes 'module blew up while loading' from 'module not found'.

Common situations: Missing a dependency (e.g. forgot to pip install Flask-SQLAlchemy in the active venv). A typo in an internal import statement. Activating the wrong virtualenv where the app's dependencies are absent. Running the CLI from a directory where relative imports fail.

Related errors


AI-assisted analysis of pallets/flask@3596b1ab61 (2026-08-11). Data as JSON: /api/errors/8958a4f30ab773b5. Report an issue: GitHub.

Appendix: source

Thrown at src/flask/cli.py:250

) -> Flask: ...


@t.overload
def locate_app(
    module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ...
) -> Flask | None: ...


def locate_app(
    module_name: str, app_name: str | None, raise_if_not_found: bool = True
) -> Flask | None:
    try:
        __import__(module_name)
    except ImportError:
        # Reraise the ImportError if it occurred within the imported module.
        # Determine this by checking whether the trace has a depth > 1.
        if sys.exc_info()[2].tb_next:  # type: ignore[union-attr]
            raise NoAppException(
                f"While importing {module_name!r}, an ImportError was"
                f" raised:\n\n{traceback.format_exc()}"
            ) from None
        elif raise_if_not_found:
            raise NoAppException(f"Could not import {module_name!r}.") from None
        else:
            return None

    module = sys.modules[module_name]

    if app_name is None:
        return find_best_app(module)
    else:
        return find_app_by_string(module, app_name)


def get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None:
    if not value or ctx.resilient_parsing:

View on GitHub (pinned to 3596b1ab61)