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
Provenance
- Commit
b837606- Tree
3b36f34- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
855d59b- Parent 2
ec1ccd7
6 files changed+136 added−8 removed
modified:docs/cli.rst+56 added
308 unmodified lines309 ::310 311 $ flask user create demo312 313+314 See :ref:`testing-cli` for an overview of how to test your custom315 commands.316 317 318+Registering Commands with Blueprints319+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~320+321+If your application uses blueprints, you can optionally register CLI322+commands directly onto them. When your blueprint is registered onto your323+application, the associated commands will be available to the ``flask``324+command. By default, those commands will be nested in a group matching325+the name of the blueprint.326+327+.. code-block:: python328+329+ from flask import Blueprint330+331+ bp = Blueprint('students', __name__)332+333+ @bp.cli.command('create')334+ @click.argument('name')335+ def create(name):336+ ...337+338+ app.register_blueprint(bp)339+340+.. code-block:: text341+342+ $ flask students create alice343+344+You can alter the group name by specifying the ``cli_group`` parameter345+when creating the :class:`Blueprint` object, or later with346+:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.347+The following are equivalent:348+349+.. code-block:: python350+351+ bp = Blueprint('students', __name__, cli_group='other')352+ # or353+ app.register_blueprint(bp, cli_group='other')354+355+.. code-block:: text356+357+ $ flask other create alice358+359+Specifying ``cli_group=None`` will remove the nesting and merge the360+commands directly to the application's level:361+362+.. code-block:: python363+364+ bp = Blueprint('students', __name__, cli_group=None)365+ # or366+ app.register_blueprint(bp, cli_group=None)367+368+.. code-block:: text369+370+ $ flask create alice371+372+373 Application Context374 ~~~~~~~~~~~~~~~~~~~375 376 Commands added using the Flask app's :attr:`~Flask.cli`167 unmodified linesmodified:flask/app.py+3 added-7 removed
598 unmodified lines599 host=static_host,600 view_func=self.send_static_file,601 )602 603- #: 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.name606 607 @locked_cached_property608 def name(self):609 """The name of the application. This is usually the import name1807 unmodified linesmodified:flask/blueprints.py+21 added
11 unmodified lines12 from functools import update_wrapper13 14 from .helpers import _PackageBoundObject, _endpoint_from_view_func15 16+# a singleton sentinel value for parameter defaults17+_sentinel = object()18 19+20 class 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 passed68 unmodified lines92 :class:`~flask.blueprints.BlueprintSetupState` later to register functions93 or other things on the main application. See :ref:`blueprints` for more94 information.95 96+ .. 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.100+101 .. versionadded:: 0.7102 """103 104 warn_on_modifications = False31 unmodified lines136 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 lines150 self.deferred_functions = []151 if url_defaults is None:152 url_defaults = {}153 self.url_values_defaults = url_defaults154+ self.cli_group = cli_group155 156 def record(self, func):157 """Registers a function that is called when the blueprint is158 registered on the application. This function is called with the56 unmodified lines215 216 for deferred in self.deferred_functions:217 deferred(state)218 219+ cli_resolved_group = options.get("cli_group", self.cli_group)220+221+ 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)229+230 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 linesmodified:flask/helpers.py+9 added
940 unmodified lines941 self.root_path = root_path942 self._static_folder = None943 self._static_url_path = None944 945+ # circular import946+ from .cli import AppGroup947+948+ #: 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()953+954 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 linesmodified:tests/test_cli.py+44 added-1 removed
21 unmodified lines22 import pytest23 from _pytest.monkeypatch import notset24 from click.testing import CliRunner25 26-from flask import Flask, current_app26+from flask import Flask, current_app, Blueprint27 from flask.cli import (28 AppGroup,29 FlaskGroup,30 NoAppException,577 unmodified lines608 609 # no --key with SSLContext610 with pytest.raises(click.BadParameter):611 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])612+613+614+def 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__)620+621+ @custom.cli.command("custom")622+ def custom_command():623+ click.echo("custom_result")624+625+ @nested.cli.command("nested")626+ def nested_command():627+ click.echo("nested_result")628+629+ @merged.cli.command("merged")630+ def merged_command():631+ click.echo("merged_result")632+633+ @late.cli.command("late")634+ def late_command():635+ click.echo("late_result")636+637+ app.register_blueprint(custom)638+ app.register_blueprint(nested)639+ app.register_blueprint(merged)640+ app.register_blueprint(late, cli_group="late_registration")641+642+ app_runner = app.test_cli_runner()643+644+ result = app_runner.invoke(args=["customized", "custom"])645+ assert "custom_result" in result.output646+647+ result = app_runner.invoke(args=["nested", "nested"])648+ assert "nested_result" in result.output649+650+ result = app_runner.invoke(args=["merged"])651+ assert "merged_result" in result.output652+653+ result = app_runner.invoke(args=["late_registration", "late"])654+ assert "late_result" in result.outputmodified:CHANGES.rst+3 added
54 unmodified lines55 - 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`.62 63 .. _#2935: https://github.com/pallets/flask/issues/293564 .. _#2957: https://github.com/pallets/flask/issues/295765 .. _#2994: https://github.com/pallets/flask/pull/2994947 unmodified lines