Greatly refactored click integration and documented it a bit more.
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 81576c2 · Browse files · 4 files·+248 added−81 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+248 added−81 removed
- other:+248 added−81 removed
Provenance
- Commit
3569fc2- Tree
da536eb- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
81576c2
4 files changed+248 added−81 removed
modified:docs/api.rst+27 added
751 unmodified lines752 app.add_url_rule('/', index)753 754 .. versionadded:: 0.8755 The `provide_automatic_options` functionality was added.756+757+Command Line Interface758+----------------------759+760+.. currentmodule:: flask.cli761+762+.. autoclass:: FlaskGroup763+ :members:764+765+.. autoclass:: ScriptInfo766+ :members:767+768+.. autofunction:: pass_script_info769+770+.. autofunction:: without_appcontext771+772+.. autofunction:: script_info_option773+774+ A special decorator that informs a click callback to be passed the775+ script info object as first argument. This is normally not useful776+ 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.779+780+.. autodata:: run_command781+782+.. autodata:: shell_commandmodified:docs/cli.rst+113 added-1 removed
106 unmodified lines107 :ref:`app-factories`) you will discover that the ``flask`` command cannot108 work with them directly. Flask won't be able to figure out how to109 instanciate your application properly by itself. Because of this reason110 the recommendation is to create a separate file that instanciates111-applications.111+applications. This is by far not the only way to make this work. Another112+is the :ref:`custom-scripts` support.113 114 For instance if you have a factory function that creates an application115 from a filename you could make a separate file that creates such an116 application from an environment variable.11 unmodified lines128 export YOURAPPLICATION_CONFIG=/path/to/config.cfg129 export FLASK_APP=/path/to/autoapp.py130 131 From this point onwards ``flask`` will find your application.132+133+.. _custom-scripts:134+135+Custom Scripts136+--------------137+138+While the most common way is to use the ``flask`` command, you can also139+make your own "driver scripts". Since Flask uses click for the scripts140+there is no reason you cannot hook these scripts into any click141+application. There is one big caveat and that is, that commands142+registered to :attr:`Flask.cli` will expect to be (indirectly at least)143+launched from a :class:`flask.cli.FlaskGroup` click group. This is144+necessary so that the commands know which Flask application they have to145+work with.146+147+To understand why you might want custom scripts you need to understand how148+click finds and executes the Flask application. If you use the ``flask``149+script you specify the application to work with on the command line or150+environment variable as an import name. This is simple but it has some151+limitations. Primarily it does not work with application factory152+functions (see :ref:`app-factories`).153+154+With a custom script you don't have this problem as you can fully155+customize how the application will be created. This is very useful if you156+write reusable applications that you want to ship to users and they should157+be presented with a custom management script.158+159+If you are used to writing click applications this will look familiar but160+at the same time, slightly different because of how commands are loaded.161+We won't go into detail now about the differences but if you are curious162+you can have a look at the :ref:`script-info-object` section to learn all163+about it.164+165+To explain all of this here an example ``manage.py`` script that manages a166+hypothetical wiki application. We will go through the details167+afterwards::168+169+ import click170+ from flask.cli import FlaskGroup, script_info_option171+172+ def create_wiki_app(info):173+ from yourwiki import create_app174+ config = info.data.get('config') or 'wikiconfig.py'175+ return create_app(config=config)176+177+ @click.group(cls=FlaskGroup, create_app=create_wiki_app)178+ @script_info_option('--config', script_info_key='config')179+ def cli(**params):180+ """This is a management script for the wiki application."""181+182+ if __name__ == '__main__':183+ cli()184+185+That's a lot of code for not much, so let's go through all parts step by186+step.187+188+1. At first we import regular ``click`` as well as the click extensions189+ from the ``flask.cli`` package. Primarily we are here interested190+ in the :class:`~flask.cli.FlaskGroup` click group and the191+ :func:`~flask.cli.script_info_option` decorator.192+2. The next thing we do is defining a function that is invoked with the193+ script info object (:ref:`script-info-object`) from flask and it's194+ purpose is to fully import and create the application. This can195+ either directly import an application object or create it (see196+ :ref:`app-factories`).197+198+ What is ``data.info``? It's a dictionary of arbitrary data on the199+ script info that can be filled by options or through other means. We200+ will come back to this later.201+3. Next step is to create a :class:`FlaskGroup`. In this case we just202+ make an empty function with a help doc string that just does nothing203+ and then pass the ``create_wiki_app`` function as factory function.204+205+ Whenever click now needs to operate on a flask application it will206+ call that function with the script info and ask for it to be created.207+4. In step 2 you could see that the config is passed to the actual208+ creation function. This config comes from the :func:`script_info_option`209+ decorator for the main script. It accepts a ``--config`` option and210+ then stores it in the script info so we can use it to create the211+ application.212+5. All is rounded up by invoking the script.213+214+.. _script-info-object:215+216+The Script Info217+---------------218+219+The Flask script integration might be confusing at first, but it has good220+rasons it's done this way. The reason for this is that Flask wants to221+both provide custom commands to click as well as not loading your222+application unless it has to. The reason for this is added flexibility.223+224+This way an application can provide custom commands, but even in the225+absence of an application the ``flask`` script is still operational on a226+basic level. In addition to that does it mean that the individual227+commands have the option to not create an instance of the Flask228+application unless required. This is very useful as it allows the server229+command for instance, the load the application on first request instead of230+immediately to give a better debug experience.231+232+All of this is provided through the :class:`flask.cli.ScriptInfo` object233+and some helper utilities around. The basic way it operates is that when234+the :class:`flask.cli.FlaskGroup` executes as a script it creates a script235+info and keeps it around. From that point onwards modifications on the236+script info can be done through click options. To simplify this pattern237+the :func:`flask.cli.script_info_option` decorator was added.238+239+One Flask actually needs the individual Flask application it will invoke240+the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the241+server starts, when the shell is launched or when the script looks for an242+application provided click command.modified:flask/cli.py+107 added-79 removed
79 unmodified lines80 sys.path.insert(0, dirpath)81 return '.'.join(module[::-1])82 83 84-def locate_app(app_id, debug=None):84+def locate_app(app_id):85 """Attempts to locate the application."""86 if ':' in app_id:87 module, app_obj = app_id.split(':', 1)88 else:8 unmodified lines97 app = getattr(mod, app_obj, None)98 if app is None:99 raise RuntimeError('Failed to find application in module "%s"'100 % module)101- if debug is not None:102- app.debug = debug101+102 return app103 104 105 class DispatchingApp(object):37 unmodified lines143 to click.144 """145 146 def __init__(self, app_import_path=None, debug=None, create_app=None):147+ #: The application import path148 self.app_import_path = app_import_path149+ #: The debug flag. If this is not None, the application will150+ #: automatically have it's debug flag overridden with this value.151 self.debug = debug152+ #: Optionally a function that is passed the script info to create153+ #: the instance of the application.154 self.create_app = create_app155+ #: A dictionary with arbitrary data that can be associated with156+ #: this script info.157+ self.data = {}158 self._loaded_app = None159 160 def load_app(self):154- """Loads the Flask app (if not yet loaded) and returns it."""161+ """Loads the Flask app (if not yet loaded) and returns it. Calling162+ this multiple times will just result in the already loaded app to163+ be returned.164+ """165 if self._loaded_app is not None:166 return self._loaded_app167 if self.create_app is not None:168 rv = self.create_app(self)169 else:170 if self.app_import_path is None:171 _no_such_app()162- rv = locate_app(self.app_import_path, self.debug)172+ rv = locate_app(self.app_import_path)173+ if self.debug is not None:174+ rv.debug = self.debug175 self._loaded_app = rv176 return rv177 166- def make_wsgi_app(self, use_eager_loading=False):167- """Returns a WSGI app that loads the actual application at a later168- stage (on first request). This has the advantage over169- :meth:`load_app` that if used with a WSGI server, it will allow170- the server to intercept errors later during request handling171- instead of dying a horrible death.172-173- If eager loading is disabled the loading will happen immediately.174- """175- if self.app_import_path is not None:176- def loader():177- return locate_app(self.app_import_path, self.debug)178- else:179- if self.create_app is None:180- _no_such_app()181- def loader():182- return self.create_app(self)183- return DispatchingApp(loader, use_eager_loading=use_eager_loading)184-178 @contextmanager179 def conditional_context(self, with_context=True):180 """Creates an application context or not, depending on the given181 parameter but always works as context manager. This is just a182 shortcut for a common operation.183 """184 if with_context:192- with self.load_app(self).app_context() as ctx:185+ with self.load_app().app_context() as ctx:186 yield ctx187 else:188 yield None189 190 198-#: A special decorator that informs a click callback to be passed the199-#: script info object as first argument. This is normally not useful200-#: unless you implement very special commands like the run command which201-#: does not want the application to be loaded yet. This can be combined202-#: with the :func:`without_appcontext` decorator.191 pass_script_info = click.make_pass_decorator(ScriptInfo)192 193 194 def without_appcontext(f):5 unmodified lines200 f.__flask_without_appcontext__ = True201 return f202 203 204+def set_debug_value(ctx, value):205+ ctx.ensure_object(ScriptInfo).debug = value206+207+208+def set_app_value(ctx, value):209+ if value is not None:210+ if os.path.isfile(value):211+ value = prepare_exec_for_file(value)212+ elif '.' not in sys.path:213+ sys.path.insert(0, '.')214+ ctx.ensure_object(ScriptInfo).app_import_path = value215+216+217+debug_option = click.Option(['--debug/--no-debug'],218+ help='Enable or disable debug mode.',219+ default=None, callback=set_debug_value)220+221+222+app_option = click.Option(['-a', '--app'],223+ help='The application to run',224+ callback=set_app_value, is_eager=True)225+226+227 class FlaskGroup(click.Group):217- """Special subclass of the a regular click group that supports218- loading more commands from the configured Flask app. Normally a219- developer does not have to interface with this class but there are220- some very advanced usecases for which it makes sense to create an221- instance of this.228+ """Special subclass of the a regular click group that supports loading229+ more commands from the configured Flask app. Normally a developer230+ does not have to interface with this class but there are some very231+ advanced usecases for which it makes sense to create an instance of232+ this.233 223- :param add_default_options: if this is True the app and debug option224- is automatically added.234+ For information as of why this is useful see :ref:`custom-scripts`.235+236+ :param add_default_commands: if this is True then the default run and237+ shell commands wil be added.238+ :param add_app_option: adds the default ``--app`` option. This gets239+ automatically disabled if a `create_app`240+ callback is defined.241+ :param add_debug_option: adds the default ``--debug`` option.242+ :param create_app: an optional callback that is passed the script info243+ and returns the loaded app.244 """245 227- def __init__(self, add_default_options=True,228- add_default_commands=True,229- create_app=None, **extra):230- click.Group.__init__(self, **extra)246+ def __init__(self, add_default_commands=True, add_app_option=None,247+ add_debug_option=True, create_app=None, **extra):248+ params = list(extra.pop('params', None) or ())249+ if add_app_option is None:250+ add_app_option = create_app is None251+ if add_app_option:252+ params.append(app_option)253+ if add_debug_option:254+ params.append(debug_option)255+256+ click.Group.__init__(self, params=params, **extra)257 self.create_app = create_app232- if add_default_options:233- self.add_app_option()234- self.add_debug_option()258+259 if add_default_commands:260 self.add_command(run_command)261 self.add_command(shell_command)262 239- def add_app_option(self):240- """Adds an option to the default command that defines an import241- path that points to an application.242- """243- def set_app_id(ctx, value):244- if value is not None:245- if os.path.isfile(value):246- value = prepare_exec_for_file(value)247- elif '.' not in sys.path:248- sys.path.insert(0, '.')249- ctx.ensure_object(ScriptInfo).app_import_path = value250-251- self.params.append(click.Option(['-a', '--app'],252- help='The application to run',253- callback=set_app_id, is_eager=True))254-255- def add_debug_option(self):256- """Adds an option that controls the debug flag."""257- def set_debug(ctx, value):258- ctx.ensure_object(ScriptInfo).debug = value259-260- self.params.append(click.Option(['--debug/--no-debug'],261- help='Enable or disable debug mode.',262- default=None, callback=set_debug))263-263 def get_command(self, ctx, name):264 info = ctx.ensure_object(ScriptInfo)265 # Find the command in the application first, if we can find it.266 # If the app is not available, we just ignore this silently.32 unmodified lines299 kwargs.setdefault('auto_envvar_prefix', 'FLASK')300 return click.Group.main(self, *args, **kwargs)301 302 303+def script_info_option(*args, **kwargs):304+ """This decorator works exactly like :func:`click.option` but is eager305+ by default and stores the value in the :attr:`ScriptInfo.data`. This306+ is useful to further customize an application factory in very complex307+ situations.308+309+ :param script_info_key: this is a mandatory keyword argument which310+ defines under which data key the value should311+ be stored.312+ """313+ try:314+ key = kwargs.pop('script_info_key')315+ except LookupError:316+ raise TypeError('script_info_key not provided.')317+318+ real_callback = kwargs.get('callback')319+ def callback(ctx, value):320+ if real_callback is not None:321+ value = real_callback(ctx, value)322+ ctx.ensure_object(ScriptInfo).data[key] = value323+ return value324+325+ kwargs['callback'] = callback326+ kwargs.setdefault('is_eager', True)327+ return click.option(*args, **kwargs)328+329+330 @click.command('run', short_help='Runs a development server.')331 @click.option('--host', '-h', default='127.0.0.1',332 help='The interface to bind to.')333 @click.option('--port', '-p', default=5000,31 unmodified lines365 debugger = info.debug366 if eager_loading is None:367 eager_loading = not reload368 343- app = info.make_wsgi_app(use_eager_loading=eager_loading)369+ app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)370 371 # Extra startup messages. This depends a but on Werkzeug internals to372 # not double execute when the reloader kicks in.373 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':39 unmodified lines413 """414 return click.Group()415 416 391-cli = FlaskGroup(help='''\392-This shell command acts as general utility script for Flask applications.417+@click.group(cls=FlaskGroup)418+def cli(**params):419+ """420+ This shell command acts as general utility script for Flask applications.421 394-It loads the application configured (either through the FLASK_APP environment395-variable or the --app parameter) and then provides commands either provided396-by the application or Flask itself.422+ It loads the application configured (either through the FLASK_APP environment423+ variable or the --app parameter) and then provides commands either provided424+ by the application or Flask itself.425 398-The most useful commands are the "run" and "shell" command.426+ The most useful commands are the "run" and "shell" command.427 400-Example usage:428+ Example usage:429 402- flask --app=hello --debug run403-''')430+ flask --app=hello --debug run431+ """432 433 434 def main(as_module=False):435 this_module = __package__ + '.cli'20 unmodified linesmodified:setup.py+1 added-1 removed
94 unmodified lines95 install_requires=[96 'Werkzeug>=0.7',97 'Jinja2>=2.4',98 'itsdangerous>=0.21',99- 'click',99+ 'click>=0.6',100 ],101 classifiers=[102 'Development Status :: 4 - Beta',103 'Environment :: Web Environment',15 unmodified lines