Refactored the scripting interface greatly.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 66ef55c · Browse files · 4 files·+64 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+64 added−35 removed
- other:+64 added−35 removed
Provenance
- Commit
932f7d7- Tree
4d53d15- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
66ef55c
4 files changed+64 added−35 removed
modified:docs/api.rst+6 added-2 removed
760 unmodified lines761 762 .. autoclass:: FlaskGroup763 :members:764 765+.. autoclass:: AppGroup766+ :members:767+768 .. autoclass:: ScriptInfo769 :members:770 771+.. autofunction:: with_appcontext772+773 .. autofunction:: pass_script_info774 775 .. autofunction:: without_appcontext776 1 unmodified line778 779 A special decorator that informs a click callback to be passed the780 script info object as first argument. This is normally not useful781 unless you implement very special commands like the run command which777- does not want the application to be loaded yet. This can be combined778- with the :func:`without_appcontext` decorator.782+ does not want the application to be loaded yet. 783 784 .. autodata:: run_command785 786 .. autodata:: shell_commandmodified:docs/cli.rst+18 added
98 unmodified lines99 100 $ flask -a hello.py initdb101 Init the db102 103+Application Context104+-------------------105+106+Most commands operate on the application so it makes a lot of sense if107+they have the application context setup. Because of this, if you register108+a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the109+callback will automatically be wrapped through :func:`cli.with_appcontext`110+which informs the cli system to ensure that an application context is set111+up. This behavior is not available if a command is lated later with112+:func:`~click.Group.add_command` or through other means.113+114+It can also be disabled by passing ``with_appcontext=False`` to the115+decorator::116+117+ @app.cli.command(with_appcontext=False)118+ def example():119+ pass120+121 Factory Functions122 -----------------123 124 In case you are using factory functions to create your application (see135 unmodified linesmodified:flask/app.py+2 added-2 removed
22 unmodified lines23 MethodNotAllowed, BadRequest24 25 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \26 locked_cached_property, _endpoint_from_view_func, find_package27-from . import json27+from . import json, cli28 from .wrappers import Request, Response29 from .config import ConfigAttribute, Config30 from .ctx import RequestContext, AppContext, _AppCtxGlobals31 from .globals import _request_ctx_stack, request, session, g511 unmodified lines543 #: application has been discovered. The default commands are544 #: provided by Flask itself and can be overridden.545 #:546 #: This is an instance of a :class:`click.Group` object.547- self.cli = click.Group(self)547+ self.cli = cli.AppGroup(self)548 549 def _get_error_handlers(self):550 from warnings import warn551 warn(DeprecationWarning('error_handlers is deprecated, use the '1372 unmodified linesmodified:flask/cli.py+38 added-31 removed
10 unmodified lines11 12 import os13 import sys14 from threading import Lock15-from contextlib import contextmanager15+from functools import update_wrapper16 17 import click18 19 from ._compat import iteritems145 unmodified lines165 rv.debug = self.debug166 self._loaded_app = rv167 return rv168 169- @contextmanager170- def conditional_context(self, with_context=True):171- """Creates an application context or not, depending on the given172- parameter but always works as context manager. This is just a173- shortcut for a common operation.174- """175- if with_context:176- with self.load_app().app_context() as ctx:177- yield ctx178- else:179- yield None169 170+pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)171 182-pass_script_info = click.make_pass_decorator(ScriptInfo)172 184-185-def without_appcontext(f):186- """Marks a click callback so that it does not get a app context187- created. This only works for commands directly registered to188- the toplevel system. This really is only useful for very189- special commands like the runserver one.173+def with_appcontext(f):174+ """Wraps a callback so that it's guaranteed to be executed with the175+ script's application context. If callbacks are registered directly176+ to the ``app.cli`` object then they are wrapped with this function177+ by default unless it's disabled.178 """191- f.__flask_without_appcontext__ = True192- return f179+ @click.pass_context180+ def decorator(__ctx, *args, **kwargs):181+ with __ctx.ensure_object(ScriptInfo).load_app().app_context():182+ return __ctx.invoke(f, *args, **kwargs)183+ return update_wrapper(decorator, f)184 185 186 def set_debug_value(ctx, param, value):187 ctx.ensure_object(ScriptInfo).debug = value22 unmodified lines210 """Special subclass of the a regular click group that supports loading211 more commands from the configured Flask app. Normally a developer212 does not have to interface with this class but there are some very213 advanced usecases for which it makes sense to create an instance of223- this.214+ this. Not to be confused with :class:`AppGroup`.215 216 For information as of why this is useful see :ref:`custom-scripts`.217 218 :param add_default_commands: if this is True then the default run and57 unmodified lines276 # the app again and this will give us the error.277 pass278 return sorted(rv)279 289- def invoke_subcommand(self, ctx, cmd, cmd_name, args):290- with_context = cmd.callback is None or \291- not getattr(cmd.callback, '__flask_without_appcontext__', False)292-293- with ctx.find_object(ScriptInfo).conditional_context(with_context):294- return click.Group.invoke_subcommand(295- self, ctx, cmd, cmd_name, args)296-280 def main(self, *args, **kwargs):281 obj = kwargs.get('obj')282 if obj is None:283 obj = ScriptInfo(create_app=self.create_app)1 unmodified line285 kwargs.setdefault('auto_envvar_prefix', 'FLASK')286 return click.Group.main(self, *args, **kwargs)287 288 289+class AppGroup(click.Group):290+ """This works similar to a regular click :class:`~click.Group` but it291+ changes the behavior of the :meth:`command` decorator so that it292+ automatically wraps the functions in :func:`with_appcontext`.293+294+ Not to be confused with :class:`FlaskGroup`.295+ """296+297+ def __init__(self, app):298+ click.Group.__init__(self)299+300+ def command(self, *args, **kwargs):301+ """This works exactly like the method of the same name on a regular302+ :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`303+ unless it's disabled by passing ``with_appcontext=False``.304+ """305+ wrap_for_ctx = kwargs.pop('with_appcontext', True)306+ def decorator(f):307+ if wrap_for_ctx:308+ f = with_appcontext(f)309+ return click.Group.command(*args, **kwargs)(f)310+ return decorator311+312+313 def script_info_option(*args, **kwargs):314 """This decorator works exactly like :func:`click.option` but is eager315 by default and stores the value in the :attr:`ScriptInfo.data`. This316 is useful to further customize an application factory in very complex35 unmodified lines352 help='Enable or disable eager loading. By default eager '353 'loading is enabled if the reloader is disabled.')354 @click.option('--with-threads/--without-threads', default=False,355 help='Enable or disable multithreading.')349-@without_appcontext356 @pass_script_info357 def run_command(info, host, port, reload, debugger, eager_loading,358 with_threads):359 """Runs a local development server for the Flask application.33 unmodified lines393 use_debugger=debugger, threaded=with_threads)394 395 396 @click.command('shell', short_help='Runs a shell in the app context.')397+@with_appcontext398 def shell_command():399 """Runs an interactive Python shell in the context of a given400 Flask application. The application will populate the default401 namespace of this shell according to it's configuration.54 unmodified lines