Support calling with_appcontext decorator with parenthesis

Calling without parenthesis still works the same. Just to have a bit more parity with Quart.
This commit is contained in:
Filip Š 2022-07-16 16:47:43 +02:00
parent 900e11850a
commit 8d62f5e8c6
3 changed files with 23 additions and 2 deletions

View file

@ -93,7 +93,8 @@ Unreleased
JSON response like a dict is. :issue:`4672`
- When type checking, allow ``TypedDict`` to be returned from view
functions. :pr:`4695`
- It is now possible to also call ``@with_appcontext`` decorator
with parenthesis, to have additional parity with Quart.
Version 2.1.3
-------------

View file

@ -408,7 +408,7 @@ class ScriptInfo:
pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)
def with_appcontext(f):
def with_appcontext(f=None):
"""Wraps a callback so that it's guaranteed to be executed with the
script's application context.
@ -416,12 +416,19 @@ def with_appcontext(f):
``blueprint.cli`` will always have an app context available, this
decorator is not required in that case.
.. versionchanged:: 2.2
It is now also possible to call the decorator with parenthesis.
.. versionchanged:: 2.2
The app context is active for subcommands as well as the
decorated callback. The app context is always available to
``app.cli`` command and parameter callbacks.
"""
# Decorator was used with parenthesis
if f is None:
return with_appcontext
@click.pass_context
def decorator(__ctx, *args, **kwargs):
if not current_app:

View file

@ -341,6 +341,19 @@ def test_with_appcontext(runner):
assert result.output == "testapp\n"
def test_with_appcontext_parenthesis(runner):
@click.command()
@with_appcontext()
def testcmd():
click.echo(current_app.name)
obj = ScriptInfo(create_app=lambda: Flask("testapp"))
result = runner.invoke(testcmd, obj=obj)
assert result.exit_code == 0
assert result.output == "testapp\n"
def test_appgroup_app_context(runner):
@click.group(cls=AppGroup)
def cli():