with_appcontext lasts for the lifetime of the click context

This commit is contained in:
David Lord 2022-06-17 11:14:22 -07:00
parent ae547270e9
commit c9e000b9ce
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
6 changed files with 65 additions and 26 deletions

View file

@ -437,12 +437,14 @@ commands directly to the application's level:
Application Context
~~~~~~~~~~~~~~~~~~~
Commands added using the Flask app's :attr:`~Flask.cli`
:meth:`~cli.AppGroup.command` decorator will be executed with an application
context pushed, so your command and extensions have access to the app and its
configuration. If you create a command using the Click :func:`~click.command`
decorator instead of the Flask decorator, you can use
:func:`~cli.with_appcontext` to get the same behavior. ::
Commands added using the Flask app's :attr:`~Flask.cli` or
:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator
will be executed with an application context pushed, so your custom
commands and parameters have access to the app and its configuration. The
:func:`~cli.with_appcontext` decorator can be used to get the same
behavior, but is not needed in most cases.
.. code-block:: python
import click
from flask.cli import with_appcontext
@ -454,12 +456,6 @@ decorator instead of the Flask decorator, you can use
app.cli.add_command(do_work)
If you're sure a command doesn't need the context, you can disable it::
@app.cli.command(with_appcontext=False)
def do_work():
...
Plugins
-------

View file

@ -40,7 +40,6 @@ response is sent.
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db():
@ -128,7 +127,6 @@ Add the Python functions that will run these SQL commands to the
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()