Skip to content
Myr

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

4 files+248 added−81 removed

modified:docs/api.rst+27 added
751 unmodified lines
752 app.add_url_rule('/', index)753754.. versionadded:: 0.8755 The `provide_automatic_options` functionality was added.756757Command Line Interface758----------------------759760.. currentmodule:: flask.cli761762.. autoclass:: FlaskGroup763 :members:764765.. autoclass:: ScriptInfo766 :members:767768.. autofunction:: pass_script_info769770.. autofunction:: without_appcontext771772.. autofunction:: script_info_option773774 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.779780.. autodata:: run_command781782.. autodata:: shell_command
modified:docs/cli.rst+113 added-1 removed
106 unmodified lines
107:ref:`app-factories`) you will discover that the ``flask`` command cannot108work with them directly. Flask won't be able to figure out how to109instanciate your application properly by itself. Because of this reason110the recommendation is to create a separate file that instanciates111applications.111applications. This is by far not the only way to make this work. Another112is the :ref:`custom-scripts` support.113114For instance if you have a factory function that creates an application115from a filename you could make a separate file that creates such an116application from an environment variable.
11 unmodified lines
128 export YOURAPPLICATION_CONFIG=/path/to/config.cfg129 export FLASK_APP=/path/to/autoapp.py130131From this point onwards ``flask`` will find your application.132133.. _custom-scripts:134135Custom Scripts136--------------137138While the most common way is to use the ``flask`` command, you can also139make your own "driver scripts". Since Flask uses click for the scripts140there is no reason you cannot hook these scripts into any click141application. There is one big caveat and that is, that commands142registered to :attr:`Flask.cli` will expect to be (indirectly at least)143launched from a :class:`flask.cli.FlaskGroup` click group. This is144necessary so that the commands know which Flask application they have to145work with.146147To understand why you might want custom scripts you need to understand how148click finds and executes the Flask application. If you use the ``flask``149script you specify the application to work with on the command line or150environment variable as an import name. This is simple but it has some151limitations. Primarily it does not work with application factory152functions (see :ref:`app-factories`).153154With a custom script you don't have this problem as you can fully155customize how the application will be created. This is very useful if you156write reusable applications that you want to ship to users and they should157be presented with a custom management script.158159If you are used to writing click applications this will look familiar but160at the same time, slightly different because of how commands are loaded.161We won't go into detail now about the differences but if you are curious162you can have a look at the :ref:`script-info-object` section to learn all163about it.164165To explain all of this here an example ``manage.py`` script that manages a166hypothetical wiki application. We will go through the details167afterwards::168169 import click170 from flask.cli import FlaskGroup, script_info_option171172 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)176177 @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."""181182 if __name__ == '__main__':183 cli()184185That's a lot of code for not much, so let's go through all parts step by186step.1871881. 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.1922. 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`).197198 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.2013. 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.204205 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.2074. 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.2125. All is rounded up by invoking the script.213214.. _script-info-object:215216The Script Info217---------------218219The Flask script integration might be confusing at first, but it has good220rasons it's done this way. The reason for this is that Flask wants to221both provide custom commands to click as well as not loading your222application unless it has to. The reason for this is added flexibility.223224This way an application can provide custom commands, but even in the225absence of an application the ``flask`` script is still operational on a226basic level. In addition to that does it mean that the individual227commands have the option to not create an instance of the Flask228application unless required. This is very useful as it allows the server229command for instance, the load the application on first request instead of230immediately to give a better debug experience.231232All of this is provided through the :class:`flask.cli.ScriptInfo` object233and some helper utilities around. The basic way it operates is that when234the :class:`flask.cli.FlaskGroup` executes as a script it creates a script235info and keeps it around. From that point onwards modifications on the236script info can be done through click options. To simplify this pattern237the :func:`flask.cli.script_info_option` decorator was added.238239One Flask actually needs the individual Flask application it will invoke240the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the241server starts, when the shell is launched or when the script looks for an242application provided click command.
modified:flask/cli.py+107 added-79 removed
79 unmodified lines
80 sys.path.insert(0, dirpath)81 return '.'.join(module[::-1])828384def locate_app(app_id, debug=None):84def 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 lines
97 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 = debug101102 return app103104105class DispatchingApp(object):
37 unmodified lines
143 to click.144 """145146 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 = None159160 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 rv177166 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.172173 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)184178 @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 None189190198#: 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.191pass_script_info = click.make_pass_decorator(ScriptInfo)192193194def without_appcontext(f):
5 unmodified lines
200 f.__flask_without_appcontext__ = True201 return f202203204def set_debug_value(ctx, value):205 ctx.ensure_object(ScriptInfo).debug = value206207208def 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 = value215216217debug_option = click.Option(['--debug/--no-debug'],218 help='Enable or disable debug mode.',219 default=None, callback=set_debug_value)220221222app_option = click.Option(['-a', '--app'],223 help='The application to run',224 callback=set_app_value, is_eager=True)225226227class 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.233223 :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`.235236 :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 """245227 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)255256 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()258259 if add_default_commands:260 self.add_command(run_command)261 self.add_command(shell_command)262239 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 = value250251 self.params.append(click.Option(['-a', '--app'],252 help='The application to run',253 callback=set_app_id, is_eager=True))254255 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 = value259260 self.params.append(click.Option(['--debug/--no-debug'],261 help='Enable or disable debug mode.',262 default=None, callback=set_debug))263263 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 lines
299 kwargs.setdefault('auto_envvar_prefix', 'FLASK')300 return click.Group.main(self, *args, **kwargs)301302303def 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.308309 :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.')317318 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 value324325 kwargs['callback'] = callback326 kwargs.setdefault('is_eager', True)327 return click.option(*args, **kwargs)328329330@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 lines
365 debugger = info.debug366 if eager_loading is None:367 eager_loading = not reload368343 app = info.make_wsgi_app(use_eager_loading=eager_loading)369 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)370371 # 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 lines
413 """414 return click.Group()415416391cli = FlaskGroup(help='''\392This shell command acts as general utility script for Flask applications.417@click.group(cls=FlaskGroup)418def cli(**params):419 """420 This shell command acts as general utility script for Flask applications.421394It loads the application configured (either through the FLASK_APP environment395variable or the --app parameter) and then provides commands either provided396by 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.425398The most useful commands are the "run" and "shell" command.426 The most useful commands are the "run" and "shell" command.427400Example usage:428 Example usage:429402 flask --app=hello --debug run403''')430 flask --app=hello --debug run431 """432433434def main(as_module=False):435 this_module = __package__ + '.cli'
20 unmodified lines
modified:setup.py+1 added-1 removed
94 unmodified lines
95 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