Skip to content
Myr

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

6 files+65 added−26 removed

modified:docs/tutorial/database.rst-2 removed
38 unmodified lines
39 import sqlite34041 import click42 from flask import current_app, g43 from flask.cli import with_appcontext434445 def get_db():46 if 'db' not in g:
79 unmodified lines
126 db.executescript(f.read().decode('utf8'))127128129 @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 lines
modified:docs/cli.rst+8 added-12 removed
435 unmodified lines
436437Application Context438~~~~~~~~~~~~~~~~~~~439440Commands added using the Flask app's :attr:`~Flask.cli`441:meth:`~cli.AppGroup.command` decorator will be executed with an application442context pushed, so your command and extensions have access to the app and its443configuration. If you create a command using the Click :func:`~click.command`444decorator instead of the Flask decorator, you can use445:func:`~cli.with_appcontext` to get the same behavior. ::440Commands added using the Flask app's :attr:`~Flask.cli` or441:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator442will be executed with an application context pushed, so your custom443commands and parameters have access to the app and its configuration. The444:func:`~cli.with_appcontext` decorator can be used to get the same445behavior, but is not needed in most cases.446447.. code-block:: python448449 import click450 from flask.cli import with_appcontext451452 @click.command()
2 unmodified lines
455 ...456457 app.cli.add_command(do_work)458457If you're sure a command doesn't need the context, you can disable it::459459 @app.cli.command(with_appcontext=False)460 def do_work():461 ...462463460Plugins461-------462463Flask will automatically load commands specified in the ``flask.commands``
141 unmodified lines
modified:examples/tutorial/flaskr/db.py-2 removed
1 unmodified line
23import click4from flask import current_app5from flask import g6from flask.cli import with_appcontext678def get_db():9 """Connect to the application's configured database. The connection
27 unmodified lines
37 db.executescript(f.read().decode("utf8"))383940@click.command("init-db")42@with_appcontext41def init_db_command():42 """Clear existing data and create new tables."""43 init_db()44 click.echo("Initialized the database.")
8 unmodified lines
modified:src/flask/cli.py+29 added-6 removed
408 unmodified lines
409410411def 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.414415 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.418419 .. 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 """424425 @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())430431 return __ctx.invoke(f, *args, **kwargs)432433 return update_wrapper(decorator, f)434435436class AppGroup(click.Group):
159 unmodified lines
596 .. versionchanged:: 2.2597 Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,598 and ``-e/--env-file`` options.599600 .. versionchanged:: 2.2601 An app context is pushed when running ``app.cli`` commands, so602 ``@with_appcontext`` is no longer required for those commands.603604 .. versionchanged:: 1.0605 If installed, python-dotenv will be used to load environment variables606 from :file:`.env` and :file:`.flaskenv` files.607 """
65 unmodified lines
673674 # 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 None681682 # 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())687688 return app.cli.get_command(ctx, name)689690 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 lines
modified:tests/test_cli.py+25 added-4 removed
11 unmodified lines
12import pytest13from _pytest.monkeypatch import notset14from click.testing import CliRunner1516from flask import _app_ctx_stack17from flask import Blueprint18from flask import current_app19from flask import Flask20from flask.cli import AppGroup
289 unmodified lines
310 with pytest.raises(BadExc):311 lazy._flush_bg_loading_exception()312313314def 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)318319 @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, value328329 cli = FlaskGroup(create_app=lambda: app)330 result = runner.invoke(cli, ["check", "x"], standalone_mode=False)331 assert result.return_value == (True, 1, True)332333334def test_with_appcontext(runner):335 @click.command()336 @with_appcontext337 def testcmd():
5 unmodified lines
343 assert result.exit_code == 0344 assert result.output == "testapp\n"345346326def test_appgroup(runner):347def test_appgroup_app_context(runner):348 @click.group(cls=AppGroup)349 def cli():350 pass351331 @cli.command(with_appcontext=True)352 @cli.command()353 def test():354 click.echo(current_app.name)355356 @cli.group()357 def subgroup():358 pass359339 @subgroup.command(with_appcontext=True)360 @subgroup.command()361 def test2():362 click.echo(current_app.name)363364 obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))
6 unmodified lines
371 assert result.exit_code == 0372 assert result.output == "testappgroup\n"373374354def test_flaskgroup(runner):375def test_flaskgroup_app_context(runner):376 def create_app():377 return Flask("flaskgroup")378379 @click.group(cls=FlaskGroup, create_app=create_app)
325 unmodified lines
modified:CHANGES.rst+3 added
31 unmodified lines
32 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`394041Version 2.1.342-------------
1291 unmodified lines