Skip to content
Myr

Merge pull request #4642 from pallets/cli-nest

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

`FlaskGroup` can be nested

authored by David Lord · committed by GitHub · parents 97298e0, aa801c4 · Browse files · 5 files+53 added−39 removed
This commit

State

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

Diff stats

5 files+53 added−39 removed

  • tests:+13 added−0 removed
  • other:+40 added−39 removed

5 files+53 added−39 removed

modified:src/flask/app.py+12 added-4 removed
8 unmodified lines
9from itertools import chain10from threading import Lock11from types import TracebackType1213import click14from werkzeug.datastructures import Headers15from werkzeug.datastructures import ImmutableDict16from werkzeug.exceptions import Aborter17from werkzeug.exceptions import BadRequest
5 unmodified lines
23from werkzeug.routing import MapAdapter24from werkzeug.routing import RequestRedirect25from werkzeug.routing import RoutingException26from werkzeug.routing import Rule27from werkzeug.serving import is_running_from_reloader28from werkzeug.urls import url_quote29from werkzeug.utils import redirect as _wz_redirect30from werkzeug.wrappers import Response as BaseResponse31
877 unmodified lines
909 .. versionchanged:: 0.10910 The default port is now picked from the ``SERVER_NAME``911 variable.912 """911 # Change this into a no-op if the server is invoked from the912 # command line. Have a look at cli.py for more information.913 # Ignore this call so that it doesn't start another server if914 # the 'flask run' command is used.915 if os.environ.get("FLASK_RUN_FROM_CLI") == "true":914 from .debughelpers import explain_ignored_app_run916 if not is_running_from_reloader():917 click.secho(918 " * Ignoring a call to 'app.run()', the server is"919 " already being run with the 'flask run' command.\n"920 " Only call 'app.run()' in an 'if __name__ =="921 ' "__main__"\' guard.',922 fg="red",923 )924916 explain_ignored_app_run()925 return926927 if get_load_dotenv(load_dotenv):928 cli.load_dotenv()
1374 unmodified lines
modified:src/flask/cli.py+25 added-20 removed
3 unmodified lines
4import platform5import re6import sys7import traceback8import typing as t9from functools import update_wrapper10from operator import attrgetter11from threading import Lock12from threading import Thread1314import click15from werkzeug.serving import is_running_from_reloader16from werkzeug.utils import import_string1718from .globals import current_app19from .helpers import get_debug_flag
254 unmodified lines
274 self._lock = Lock()275 self._bg_loading_exc = None276277 if use_eager_loading is None:276 use_eager_loading = os.environ.get("WERKZEUG_RUN_MAIN") != "true"278 use_eager_loading = not is_running_from_reloader()279280 if use_eager_loading:281 self._load_unlocked()282 else:
195 unmodified lines
478479 if add_version_option:480 params.append(version_option)481480 AppGroup.__init__(self, params=params, **extra)482 if "context_settings" not in extra:483 extra["context_settings"] = {}484485 extra["context_settings"].setdefault("auto_envvar_prefix", "FLASK")486487 super().__init__(params=params, **extra)488489 self.create_app = create_app490 self.load_dotenv = load_dotenv491 self.set_debug_flag = set_debug_flag492
59 unmodified lines
552 click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")553554 return sorted(rv)555548 def main(self, *args, **kwargs):549 # Set a global flag that indicates that we were invoked from the550 # command line interface. This is detected by Flask.run to make the551 # call into a no-op. This is necessary to avoid ugly errors when the552 # script that is loaded here also attempts to start a server.553 os.environ["FLASK_RUN_FROM_CLI"] = "true"554556 def make_context(557 self,558 info_name: t.Optional[str],559 args: t.List[str],560 parent: t.Optional[click.Context] = None,561 **extra: t.Any,562 ) -> click.Context:563 if get_load_dotenv(self.load_dotenv):564 load_dotenv()565558 obj = kwargs.get("obj")559560 if obj is None:561 obj = ScriptInfo(566 if "obj" not in extra and "obj" not in self.context_settings:567 extra["obj"] = ScriptInfo(568 create_app=self.create_app, set_debug_flag=self.set_debug_flag569 )570565 kwargs["obj"] = obj566 kwargs.setdefault("auto_envvar_prefix", "FLASK")567 return super().main(*args, **kwargs)571 return super().make_context(info_name, args, parent=parent, **extra)572573574def _path_is_ancestor(path, other):575 """Take ``other`` and remove the length of ``path`` from it. Then join it
64 unmodified lines
640def show_server_banner(env, debug, app_import_path, eager_loading):641 """Show extra startup messages the first time the server is run,642 ignoring the reloader.643 """640 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":644 if is_running_from_reloader():645 return646647 if app_import_path is not None:648 message = f" * Serving Flask app {app_import_path!r}"
7 unmodified lines
656657 if env == "production":658 click.secho(659 " WARNING: This is a development server. Do not use it in"656 " a production deployment.",660 " a production deployment.\n Use a production WSGI server"661 " instead.",662 fg="red",663 )659 click.secho(" Use a production WSGI server instead.", dim=True)664665 if debug is not None:666 click.echo(f" * Debug mode: {'on' if debug else 'off'}")667
298 unmodified lines
966 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())967968969cli = FlaskGroup(970 name="flask",971 help="""\972A general utility script for Flask applications.973974Provides commands from Flask, extensions, and the application. Loads the
7 unmodified lines
982 {prefix}flask run983""".format(984 cmd="export" if os.name == "posix" else "set",985 prefix="$ " if os.name == "posix" else "> ",981 )986 ),987)988989990def main() -> None:
5 unmodified lines
modified:src/flask/debughelpers.py-15 removed
1import os1import typing as t3from warnings import warn23from .app import Flask4from .blueprints import Blueprint5from .globals import _request_ctx_stack
150 unmodified lines
156 info.append(" Maybe you did not place a template in the right folder?")157 info.append(" See https://flask.palletsprojects.com/blueprints/#templates")158159 app.logger.info("\n".join(info))162163164def explain_ignored_app_run() -> None:165 if os.environ.get("WERKZEUG_RUN_MAIN") != "true":166 warn(167 Warning(168 "Silently ignoring app.run() because the application is"169 " run from the flask command line executable. Consider"170 ' putting app.run() behind an if __name__ == "__main__"'171 " guard to silence this warning."172 ),173 stacklevel=3,174 )
modified:tests/test_cli.py+13 added
386 unmodified lines
387 assert result.exit_code == 0388 assert result.output == f"{not set_debug_flag}\n"389390391def test_flaskgroup_nested(app, runner):392 cli = click.Group("cli")393 flask_group = FlaskGroup(name="flask", create_app=lambda: app)394 cli.add_command(flask_group)395396 @flask_group.command()397 def show():398 click.echo(current_app.name)399400 result = runner.invoke(cli, ["flask", "show"])401 assert result.output == "flask_test\n"402403404def test_no_command_echo_loading_error():405 from flask.cli import cli406407 runner = CliRunner(mix_stderr=False)
276 unmodified lines
modified:CHANGES.rst+3 added
23 unmodified lines
24 the application instead. :issue:`4605`25- Added the ``View.init_every_request`` class attribute. If a view26 subclass sets this to ``False``, the view will not create a new27 instance on every request. :issue:`2520`.28- A ``flask.cli.FlaskGroup`` Click group can be nested as a29 sub-command in a custom CLI. :issue:`3263`303132Version 2.1.333-------------3435Unreleased
1289 unmodified lines