Skip to content
Myr

Merge pull request #3711 from pallets/cli-loading-error

Before adoption: this commit came in with the history the project adopted, so no landing records it.

cleaner message when CLI can't load app

authored by David Lord · committed by GitHub · parents fd0a608, 2535707 · Browse files · 4 files+58 added−37 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+58 added−37 removed

  • tests:+34 added−13 removed
  • other:+24 added−24 removed

4 files+58 added−37 removed

modified:src/flask/cli.py+22 added-24 removed
534 unmodified lines
535 self._loaded_plugin_commands = True536537 def get_command(self, ctx, name):538 self._load_plugin_commands()539 # Look up built-in and plugin commands, which should be540 # available even if the app fails to load.541 rv = super().get_command(ctx, name)542540 # We load built-in commands first as these should always be the541 # same no matter what the app does. If the app does want to542 # override this it needs to make a custom instance of this group543 # and not attach the default commands.544 #545 # This also means that the script stays functional in case the546 # application completely fails.547 rv = AppGroup.get_command(self, ctx, name)543 if rv is not None:544 return rv545546 info = ctx.ensure_object(ScriptInfo)547548 # Look up commands provided by the app, showing an error and549 # continuing if the app couldn't be loaded.550 try:553 rv = info.load_app().cli.get_command(ctx, name)554 if rv is not None:555 return rv556 except NoAppException:557 pass551 return info.load_app().cli.get_command(ctx, name)552 except NoAppException as e:553 click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")554555 def list_commands(self, ctx):556 self._load_plugin_commands()561562 # The commands available is the list of both the application (if563 # available) plus the builtin commands.564 rv = set(click.Group.list_commands(self, ctx))557 # Start with the built-in and plugin commands.558 rv = set(super().list_commands(ctx))559 info = ctx.ensure_object(ScriptInfo)560561 # Add commands provided by the app, showing an error and562 # continuing if the app couldn't be loaded.563 try:564 rv.update(info.load_app().cli.list_commands(ctx))565 except NoAppException as e:566 # When an app couldn't be loaded, show the error message567 # without the traceback.568 click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")569 except Exception:569 # Here we intentionally swallow all exceptions as we don't570 # want the help page to break if the app does not exist.571 # If someone attempts to use the command we try to create572 # the app again and this will give us the error.573 # However, we will not do so silently because that would confuse574 # users.575 traceback.print_exc()570 # When any other errors occurred during loading, show the571 # full traceback.572 click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")573574 return sorted(rv)575576 def main(self, *args, **kwargs):577 # Set a global flag that indicates that we were invoked from the
385 unmodified lines
modified:tests/conftest.py+9 added-3 removed
71 unmodified lines
727374@pytest.fixture75def test_apps(monkeypatch):76 monkeypatch.syspath_prepend(77 os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))78 )76 monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), "test_apps"))77 original_modules = set(sys.modules.keys())7879 yield8081 # Remove any imports cached during the test. Otherwise "import app"82 # will work in the next test even though it's no longer on the path.83 for key in sys.modules.keys() - original_modules:84 sys.modules.pop(key)858687@pytest.fixture(autouse=True)88def leak_detector():89 yield90
107 unmodified lines
modified:tests/test_cli.py+25 added-10 removed
237 unmodified lines
238 with pytest.raises(NoAppException):239 locate_app(info, iname, aname)240241242def test_locate_app_suppress_raise():242def test_locate_app_suppress_raise(test_apps):243 info = ScriptInfo()244 app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)245 assert app is None246
148 unmodified lines
395 assert result.exit_code == 0396 assert result.output == f"{not set_debug_flag}\n"397398399def test_print_exceptions(runner):400 """Print the stacktrace if the CLI."""399def test_no_command_echo_loading_error():400 from flask.cli import cli401402 runner = CliRunner(mix_stderr=False)403 result = runner.invoke(cli, ["missing"])404 assert result.exit_code == 2405 assert "FLASK_APP" in result.stderr406 assert "Usage:" in result.stderr407408409def test_help_echo_loading_error():410 from flask.cli import cli411412 runner = CliRunner(mix_stderr=False)413 result = runner.invoke(cli, ["--help"])414 assert result.exit_code == 0415 assert "FLASK_APP" in result.stderr416 assert "Usage:" in result.stdout417418419def test_help_echo_exception():420 def create_app():421 raise Exception("oh no")404 return Flask("flaskgroup")422406 @click.group(cls=FlaskGroup, create_app=create_app)407 def cli(**params):408 pass409423 cli = FlaskGroup(create_app=create_app)424 runner = CliRunner(mix_stderr=False)425 result = runner.invoke(cli, ["--help"])426 assert result.exit_code == 0412 assert "Exception: oh no" in result.output413 assert "Traceback" in result.output427 assert "Exception: oh no" in result.stderr428 assert "Usage:" in result.stdout429430431class TestRoutes:432 @pytest.fixture
229 unmodified lines
modified:CHANGES.rst+2 added
10 unmodified lines
11- The ``encoding`` option to JSON functions is deprecated. :pr:`3562`12- Passing ``script_info`` to app factory functions is deprecated. This13 was not portable outside the ``flask`` command. Use14 ``click.get_current_context().obj`` if it's needed. :issue:`3552`15- The CLI shows better error messages when the app failed to load16 when looking up commands. :issue:`2741`17- Add :meth:`sessions.SessionInterface.get_cookie_name` to allow18 setting the session cookie name dynamically. :pr:`3369`19- Add :meth:`Config.from_file` to load config using arbitrary file20 loaders, such as ``toml.load`` or ``json.load``.
1043 unmodified lines