Skip to content
Myr

Merge pull request #2784 from doobeh/master

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

Add Blueprint level cli registration-- #1357

authored by David Lord · committed by GitHub · parents 855d59b, ec1ccd7 · Browse files · 6 files+136 added−8 removed
This commit

State

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

Diff stats

6 files+136 added−8 removed

  • tests:+44 added−1 removed
  • other:+92 added−7 removed

6 files+136 added−8 removed

modified:docs/cli.rst+56 added
308 unmodified lines
309::310311 $ flask user create demo312313314See :ref:`testing-cli` for an overview of how to test your custom315commands.316317318Registering Commands with Blueprints319~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~320321If your application uses blueprints, you can optionally register CLI322commands directly onto them. When your blueprint is registered onto your323application, the associated commands will be available to the ``flask``324command. By default, those commands will be nested in a group matching325the name of the blueprint.326327.. code-block:: python328329 from flask import Blueprint330331 bp = Blueprint('students', __name__)332333 @bp.cli.command('create')334 @click.argument('name')335 def create(name):336 ...337338 app.register_blueprint(bp)339340.. code-block:: text341342 $ flask students create alice343344You can alter the group name by specifying the ``cli_group`` parameter345when creating the :class:`Blueprint` object, or later with346:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.347The following are equivalent:348349.. code-block:: python350351 bp = Blueprint('students', __name__, cli_group='other')352 # or353 app.register_blueprint(bp, cli_group='other')354355.. code-block:: text356357 $ flask other create alice358359Specifying ``cli_group=None`` will remove the nesting and merge the360commands directly to the application's level:361362.. code-block:: python363364 bp = Blueprint('students', __name__, cli_group=None)365 # or366 app.register_blueprint(bp, cli_group=None)367368.. code-block:: text369370 $ flask create alice371372373Application Context374~~~~~~~~~~~~~~~~~~~375376Commands added using the Flask app's :attr:`~Flask.cli`
167 unmodified lines
modified:flask/app.py+3 added-7 removed
598 unmodified lines
599 host=static_host,600 view_func=self.send_static_file,601 )602603 #: The click command line context for this application. Commands604 #: registered here show up in the :command:`flask` command once the605 #: application has been discovered. The default commands are606 #: provided by Flask itself and can be overridden.607 #:608 #: This is an instance of a :class:`click.Group` object.609 self.cli = cli.AppGroup(self.name)603 # Set the name of the Click group in case someone wants to add604 # the app's commands to another CLI tool.605 self.cli.name = self.name606607 @locked_cached_property608 def name(self):609 """The name of the application. This is usually the import name
1807 unmodified lines
modified:flask/blueprints.py+21 added
11 unmodified lines
12from functools import update_wrapper1314from .helpers import _PackageBoundObject, _endpoint_from_view_func1516# a singleton sentinel value for parameter defaults17_sentinel = object()181920class BlueprintSetupState(object):21 """Temporary holder object for registering a blueprint with the22 application. An instance of this class is created by the23 :meth:`~flask.Blueprint.make_setup_state` method and later passed
68 unmodified lines
92 :class:`~flask.blueprints.BlueprintSetupState` later to register functions93 or other things on the main application. See :ref:`blueprints` for more94 information.9596 .. versionchanged:: 1.1.097 Blueprints have a ``cli`` group to register nested CLI commands.98 The ``cli_group`` parameter controls the name of the group under99 the ``flask`` command.100101 .. versionadded:: 0.7102 """103104 warn_on_modifications = False
31 unmodified lines
136 url_prefix=None,137 subdomain=None,138 url_defaults=None,139 root_path=None,140 cli_group=_sentinel,141 ):142 _PackageBoundObject.__init__(143 self, import_name, template_folder, root_path=root_path144 )
5 unmodified lines
150 self.deferred_functions = []151 if url_defaults is None:152 url_defaults = {}153 self.url_values_defaults = url_defaults154 self.cli_group = cli_group155156 def record(self, func):157 """Registers a function that is called when the blueprint is158 registered on the application. This function is called with the
56 unmodified lines
215216 for deferred in self.deferred_functions:217 deferred(state)218219 cli_resolved_group = options.get("cli_group", self.cli_group)220221 if cli_resolved_group is None:222 app.cli.commands.update(self.cli.commands)223 elif cli_resolved_group is _sentinel:224 self.cli.name = self.name225 app.cli.add_command(self.cli)226 else:227 self.cli.name = cli_resolved_group228 app.cli.add_command(self.cli)229230 def route(self, rule, **options):231 """Like :meth:`Flask.route` but for a blueprint. The endpoint for the232 :func:`url_for` function is prefixed with the name of the blueprint.233 """
294 unmodified lines
modified:flask/helpers.py+9 added
940 unmodified lines
941 self.root_path = root_path942 self._static_folder = None943 self._static_url_path = None944945 # circular import946 from .cli import AppGroup947948 #: The Click command group for registration of CLI commands949 #: on the application and associated blueprints. These commands950 #: are accessible via the :command:`flask` command once the951 #: application has been discovered and blueprints registered.952 self.cli = AppGroup()953954 def _get_static_folder(self):955 if self._static_folder is not None:956 return os.path.join(self.root_path, self._static_folder)957
155 unmodified lines
modified:tests/test_cli.py+44 added-1 removed
21 unmodified lines
22import pytest23from _pytest.monkeypatch import notset24from click.testing import CliRunner2526from flask import Flask, current_app26from flask import Flask, current_app, Blueprint27from flask.cli import (28 AppGroup,29 FlaskGroup,30 NoAppException,
577 unmodified lines
608609 # no --key with SSLContext610 with pytest.raises(click.BadParameter):611 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])612613614def test_cli_blueprints(app):615 """Test blueprint commands register correctly to the application"""616 custom = Blueprint("custom", __name__, cli_group="customized")617 nested = Blueprint("nested", __name__)618 merged = Blueprint("merged", __name__, cli_group=None)619 late = Blueprint("late", __name__)620621 @custom.cli.command("custom")622 def custom_command():623 click.echo("custom_result")624625 @nested.cli.command("nested")626 def nested_command():627 click.echo("nested_result")628629 @merged.cli.command("merged")630 def merged_command():631 click.echo("merged_result")632633 @late.cli.command("late")634 def late_command():635 click.echo("late_result")636637 app.register_blueprint(custom)638 app.register_blueprint(nested)639 app.register_blueprint(merged)640 app.register_blueprint(late, cli_group="late_registration")641642 app_runner = app.test_cli_runner()643644 result = app_runner.invoke(args=["customized", "custom"])645 assert "custom_result" in result.output646647 result = app_runner.invoke(args=["nested", "nested"])648 assert "nested_result" in result.output649650 result = app_runner.invoke(args=["merged"])651 assert "merged_result" in result.output652653 result = app_runner.invoke(args=["late_registration", "late"])654 assert "late_result" in result.output
modified:CHANGES.rst+3 added
54 unmodified lines
55- Allow returning a dictionary from a view function. Similar to how56 returning a string will produce a ``text/html`` response, returning57 a dict will call ``jsonify`` to produce a ``application/json``58 response. :pr:`3111`59- Blueprints have a ``cli`` Click group like ``app.cli``. CLI commands60 registered with a blueprint will be available as a group under the61 ``flask`` command. :issue:`1357`.6263.. _#2935: https://github.com/pallets/flask/issues/293564.. _#2957: https://github.com/pallets/flask/issues/295765.. _#2994: https://github.com/pallets/flask/pull/2994
947 unmodified lines