with_appcontext lasts for the lifetime of the click context
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent ae54727 · Browse files · 6 files·+65 added−26 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+65 added−26 removed
- tests:+25 added−4 removed
- other:+40 added−22 removed
Provenance
- Commit
c9e000b- Tree
9866b15- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
ae54727
6 files changed+65 added−26 removed
modified:docs/tutorial/database.rst-2 removed
38 unmodified lines39 import sqlite340 41 import click42 from flask import current_app, g43- from flask.cli import with_appcontext43 44 45 def get_db():46 if 'db' not in g:79 unmodified lines126 db.executescript(f.read().decode('utf8'))127 128 129 @click.command('init-db')131- @with_appcontext130 def init_db_command():131 """Clear the existing data and create new tables."""132 init_db()133 click.echo('Initialized the database.')76 unmodified linesmodified:docs/cli.rst+8 added-12 removed
435 unmodified lines436 437 Application Context438 ~~~~~~~~~~~~~~~~~~~439 440-Commands added using the Flask app's :attr:`~Flask.cli`441-:meth:`~cli.AppGroup.command` decorator will be executed with an application442-context pushed, so your command and extensions have access to the app and its443-configuration. If you create a command using the Click :func:`~click.command`444-decorator instead of the Flask decorator, you can use445-:func:`~cli.with_appcontext` to get the same behavior. ::440+Commands added using the Flask app's :attr:`~Flask.cli` or441+:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator442+will be executed with an application context pushed, so your custom443+commands and parameters have access to the app and its configuration. The444+:func:`~cli.with_appcontext` decorator can be used to get the same445+behavior, but is not needed in most cases.446 447+.. code-block:: python448+449 import click450 from flask.cli import with_appcontext451 452 @click.command()2 unmodified lines455 ...456 457 app.cli.add_command(do_work)458 457-If you're sure a command doesn't need the context, you can disable it::459 459- @app.cli.command(with_appcontext=False)460- def do_work():461- ...462-463-460 Plugins461 -------462 463 Flask will automatically load commands specified in the ``flask.commands``141 unmodified linesmodified:examples/tutorial/flaskr/db.py-2 removed
1 unmodified line2 3 import click4 from flask import current_app5 from flask import g6-from flask.cli import with_appcontext6 7 8 def get_db():9 """Connect to the application's configured database. The connection27 unmodified lines37 db.executescript(f.read().decode("utf8"))38 39 40 @click.command("init-db")42-@with_appcontext41 def init_db_command():42 """Clear existing data and create new tables."""43 init_db()44 click.echo("Initialized the database.")8 unmodified linesmodified:src/flask/cli.py+29 added-6 removed
408 unmodified lines409 410 411 def with_appcontext(f):412 """Wraps a callback so that it's guaranteed to be executed with the413- script's application context. If callbacks are registered directly414- to the ``app.cli`` object then they are wrapped with this function415- by default unless it's disabled.413+ script's application context.414+415+ Custom commands (and their options) registered under ``app.cli`` or416+ ``blueprint.cli`` will always have an app context available, this417+ decorator is not required in that case.418+419+ .. versionchanged:: 2.2420+ The app context is active for subcommands as well as the421+ decorated callback. The app context is always available to422+ ``app.cli`` command and parameter callbacks.423 """424 425 @click.pass_context426 def decorator(__ctx, *args, **kwargs):420- with __ctx.ensure_object(ScriptInfo).load_app().app_context():421- return __ctx.invoke(f, *args, **kwargs)427+ if not current_app:428+ app = __ctx.ensure_object(ScriptInfo).load_app()429+ __ctx.with_resource(app.app_context())430 431+ return __ctx.invoke(f, *args, **kwargs)432+433 return update_wrapper(decorator, f)434 435 436 class AppGroup(click.Group):159 unmodified lines596 .. versionchanged:: 2.2597 Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,598 and ``-e/--env-file`` options.599 600+ .. versionchanged:: 2.2601+ An app context is pushed when running ``app.cli`` commands, so602+ ``@with_appcontext`` is no longer required for those commands.603+604 .. versionchanged:: 1.0605 If installed, python-dotenv will be used to load environment variables606 from :file:`.env` and :file:`.flaskenv` files.607 """65 unmodified lines673 674 # Look up commands provided by the app, showing an error and675 # continuing if the app couldn't be loaded.676 try:663- return info.load_app().cli.get_command(ctx, name)677+ app = info.load_app()678 except NoAppException as e:679 click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")680+ return None681 682+ # Push an app context for the loaded app unless it is already683+ # active somehow. This makes the context available to parameter684+ # and command callbacks without needing @with_appcontext.685+ if not current_app or current_app._get_current_object() is not app:686+ ctx.with_resource(app.app_context())687+688+ return app.cli.get_command(ctx, name)689+690 def list_commands(self, ctx):691 self._load_plugin_commands()692 # Start with the built-in and plugin commands.693 rv = set(super().list_commands(ctx))462 unmodified linesmodified:tests/test_cli.py+25 added-4 removed
11 unmodified lines12 import pytest13 from _pytest.monkeypatch import notset14 from click.testing import CliRunner15 16+from flask import _app_ctx_stack17 from flask import Blueprint18 from flask import current_app19 from flask import Flask20 from flask.cli import AppGroup289 unmodified lines310 with pytest.raises(BadExc):311 lazy._flush_bg_loading_exception()312 313 314+def test_app_cli_has_app_context(app, runner):315+ def _param_cb(ctx, param, value):316+ # current_app should be available in parameter callbacks317+ return bool(current_app)318+319+ @app.cli.command()320+ @click.argument("value", callback=_param_cb)321+ def check(value):322+ app = click.get_current_context().obj.load_app()323+ # the loaded app should be the same as current_app324+ same_app = current_app._get_current_object() is app325+ # only one app context should be pushed326+ stack_size = len(_app_ctx_stack._local.stack)327+ return same_app, stack_size, value328+329+ cli = FlaskGroup(create_app=lambda: app)330+ result = runner.invoke(cli, ["check", "x"], standalone_mode=False)331+ assert result.return_value == (True, 1, True)332+333+334 def test_with_appcontext(runner):335 @click.command()336 @with_appcontext337 def testcmd():5 unmodified lines343 assert result.exit_code == 0344 assert result.output == "testapp\n"345 346 326-def test_appgroup(runner):347+def test_appgroup_app_context(runner):348 @click.group(cls=AppGroup)349 def cli():350 pass351 331- @cli.command(with_appcontext=True)352+ @cli.command()353 def test():354 click.echo(current_app.name)355 356 @cli.group()357 def subgroup():358 pass359 339- @subgroup.command(with_appcontext=True)360+ @subgroup.command()361 def test2():362 click.echo(current_app.name)363 364 obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))6 unmodified lines371 assert result.exit_code == 0372 assert result.output == "testappgroup\n"373 374 354-def test_flaskgroup(runner):375+def test_flaskgroup_app_context(runner):376 def create_app():377 return Flask("flaskgroup")378 379 @click.group(cls=FlaskGroup, create_app=create_app)325 unmodified linesmodified:CHANGES.rst+3 added
31 unmodified lines32 variables. :issue:`2836`33 - Add ``--env-file`` option to the ``flask`` CLI. This allows34 specifying a dotenv file to load in addition to ``.env`` and35 ``.flaskenv``. :issue:`3108`36+- It is no longer required to decorate custom CLI commands on37+ ``app.cli`` or ``blueprint.cli`` with ``@with_appcontext``, an app38+ context will already be active at that point. :issue:`2410`39 40 41 Version 2.1.342 -------------1291 unmodified lines