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
Provenance
- Commit
fe4003b- Tree
3750d44- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
97298e0- Parent 2
aa801c4
5 files changed+53 added−39 removed
modified:src/flask/app.py+12 added-4 removed
8 unmodified lines9 from itertools import chain10 from threading import Lock11 from types import TracebackType12 13+import click14 from werkzeug.datastructures import Headers15 from werkzeug.datastructures import ImmutableDict16 from werkzeug.exceptions import Aborter17 from werkzeug.exceptions import BadRequest5 unmodified lines23 from werkzeug.routing import MapAdapter24 from werkzeug.routing import RequestRedirect25 from werkzeug.routing import RoutingException26 from werkzeug.routing import Rule27+from werkzeug.serving import is_running_from_reloader28 from werkzeug.urls import url_quote29 from werkzeug.utils import redirect as _wz_redirect30 from werkzeug.wrappers import Response as BaseResponse31 877 unmodified lines909 .. 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+ )924 916- explain_ignored_app_run()925 return926 927 if get_load_dotenv(load_dotenv):928 cli.load_dotenv()1374 unmodified linesmodified:src/flask/cli.py+25 added-20 removed
3 unmodified lines4 import platform5 import re6 import sys7 import traceback8+import typing as t9 from functools import update_wrapper10 from operator import attrgetter11 from threading import Lock12 from threading import Thread13 14 import click15+from werkzeug.serving import is_running_from_reloader16 from werkzeug.utils import import_string17 18 from .globals import current_app19 from .helpers import get_debug_flag254 unmodified lines274 self._lock = Lock()275 self._bg_loading_exc = None276 277 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()279 280 if use_eager_loading:281 self._load_unlocked()282 else:195 unmodified lines478 479 if add_version_option:480 params.append(version_option)481 480- AppGroup.__init__(self, params=params, **extra)482+ if "context_settings" not in extra:483+ extra["context_settings"] = {}484+485+ extra["context_settings"].setdefault("auto_envvar_prefix", "FLASK")486+487+ super().__init__(params=params, **extra)488+489 self.create_app = create_app490 self.load_dotenv = load_dotenv491 self.set_debug_flag = set_debug_flag492 59 unmodified lines552 click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")553 554 return sorted(rv)555 548- 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"554-556+ 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()565 558- obj = kwargs.get("obj")559-560- 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 )570 565- 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)572 573 574 def _path_is_ancestor(path, other):575 """Take ``other`` and remove the length of ``path`` from it. Then join it64 unmodified lines640 def 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 return646 647 if app_import_path is not None:648 message = f" * Serving Flask app {app_import_path!r}"7 unmodified lines656 657 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)664 665 if debug is not None:666 click.echo(f" * Debug mode: {'on' if debug else 'off'}")667 298 unmodified lines966 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())967 968 969 cli = FlaskGroup(970+ name="flask",971 help="""\972 A general utility script for Flask applications.973 974 Provides commands from Flask, extensions, and the application. Loads the7 unmodified lines982 {prefix}flask run983 """.format(984 cmd="export" if os.name == "posix" else "set",985 prefix="$ " if os.name == "posix" else "> ",981- )986+ ),987 )988 989 990 def main() -> None:5 unmodified linesmodified:src/flask/debughelpers.py-15 removed
1-import os1 import typing as t3-from warnings import warn2 3 from .app import Flask4 from .blueprints import Blueprint5 from .globals import _request_ctx_stack150 unmodified lines156 info.append(" Maybe you did not place a template in the right folder?")157 info.append(" See https://flask.palletsprojects.com/blueprints/#templates")158 159 app.logger.info("\n".join(info))162-163-164-def 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 lines387 assert result.exit_code == 0388 assert result.output == f"{not set_debug_flag}\n"389 390 391+def 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)395+396+ @flask_group.command()397+ def show():398+ click.echo(current_app.name)399+400+ result = runner.invoke(cli, ["flask", "show"])401+ assert result.output == "flask_test\n"402+403+404 def test_no_command_echo_loading_error():405 from flask.cli import cli406 407 runner = CliRunner(mix_stderr=False)276 unmodified linesmodified:CHANGES.rst+3 added
23 unmodified lines24 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`30 31+32 Version 2.1.333 -------------34 35 Unreleased1289 unmodified lines