Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

259 lines · 10.1 KiB

Last changed by

Merge pull request #1263 from its-not-a-bug-its-a-feature/patch-1Markus Unterwaditzerbefore adoption924763a

History of this file

Take it

The walk stopped after 200 commits: lines older than 0a7cc2b point at it.

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 1–17why, one step back
1.. _cli:
23Command Line Interface4======================56.. versionadded:: 1.078.. currentmodule:: flask910One of the nice new features in Flask 1.0 is the built-in integration of11the `click <http://click.pocoo.org/>`_ command line interface. This12enables a wide range of new features for the Flask ecosystem and your own13applications.1415Basic Usage16-----------17

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 18why, one step back
18After installation of Flask you will now find a :command:`flask` script installed

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 19–27why, one step back
19into your virtualenv. If you don't want to install Flask or you have a
20special use-case you can also use ``python -m flask`` to accomplish exactly21the same.2223The way this script works is by providing access to all the commands on24your Flask application's :attr:`Flask.cli` instance as well as some25built-in commands that are always there. Flask extensions can also26register more commands there if they desire so.27

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 28why, one step back
28For the :command:`flask` script to work, an application needs to be discovered.

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

line 29why, one step back
29The two most common ways are either an environment variable

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 30why, one step back
30(``FLASK_APP``) or the :option:`--app` / :option:`-a` parameter. It should be the

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 31–37why, one step back
31import path for your application or the path to a Python file. In the
32latter case Flask will attempt to setup the Python path for you33automatically and discover the module name but that might not always work.3435In that imported file the name of the app needs to be called ``app`` or36optionally be specified after a colon.37

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 38why, one step back
38Given a :file:`hello.py` file with the application in it named ``app`` this is

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 39–64why, one step back
39how it can be run.
4041Environment variables (On Windows use ``set`` instead of ``export``)::4243 export FLASK_APP=hello44 flask run4546Parameters::4748 flask --app=hello run4950File names::5152 flask --app=hello.py run5354Virtualenv Integration55----------------------5657If you are constantly working with a virtualenv you can also put the58``export FLASK_APP`` into your ``activate`` script by adding it to the59bottom of the file. That way every time you activate your virtualenv you60automatically also activate the correct application name.6162Debug Flag63----------64

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 65why, one step back
65The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` to

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 66–110why, one step back
66automatically flip the debug flag of the application. This can also be
67configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.6869Running a Shell70---------------7172To run an interactive Python shell you can use the ``shell`` command::7374 flask --app=hello shell7576This will start up an interactive Python shell, setup the correct77application context and setup the local variables in the shell. This is78done by invoking the :meth:`Flask.make_shell_context` method of the79application. By default you have access to your ``app`` and :data:`g`.8081Custom Commands82---------------8384If you want to add more commands to the shell script you can do this85easily. Flask uses `click`_ for the command interface which makes86creating custom commands very easy. For instance if you want a shell87command to initialize the database you can do this::8889 from flask import Flask9091 app = Flask(__name__)9293 @app.cli.command()94 def initdb():95 """Initialize the database."""96 print 'Init the db'9798The command will then show up on the command line::99100 $ flask -a hello.py initdb101 Init the db102103Application Context104-------------------105106Most commands operate on the application so it makes a lot of sense if107they have the application context setup. Because of this, if you register108a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the109callback will automatically be wrapped through :func:`cli.with_appcontext`110which informs the cli system to ensure that an application context is set

Merge pull request #1217 from jeffwidman/patch-1Markus Unterwaditzerbefore adoption7b3e52b

line 111why, one step back
111up. This behavior is not available if a command is added later with

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 112–124why, one step back
112:func:`~click.Group.add_command` or through other means.
113114It can also be disabled by passing ``with_appcontext=False`` to the115decorator::116117 @app.cli.command(with_appcontext=False)118 def example():119 pass120121Factory Functions122-----------------123124In case you are using factory functions to create your application (see

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 125why, one step back
125:ref:`app-factories`) you will discover that the :command:`flask` command cannot

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 126–135why, one step back
126work with them directly. Flask won't be able to figure out how to
127instantiate your application properly by itself. Because of this reason128the recommendation is to create a separate file that instantiates129applications. This is by far not the only way to make this work. Another130is the :ref:`custom-scripts` support.131132For instance if you have a factory function that creates an application133from a filename you could make a separate file that creates such an134application from an environment variable.135

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 136why, one step back
136This could be a file named :file:`autoapp.py` with these contents::

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 137–147why, one step back
137
138 import os139 from yourapplication import create_app140 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])141142Once this has happened you can make the flask command automatically pick143it up::144145 export YOURAPPLICATION_CONFIG=/path/to/config.cfg146 export FLASK_APP=/path/to/autoapp.py147

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 148why, one step back
148From this point onwards :command:`flask` will find your application.

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 149–154why, one step back
149
150.. _custom-scripts:151152Custom Scripts153--------------154

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 155why, one step back
155While the most common way is to use the :command:`flask` command, you can also

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 156–164why, one step back
156make your own "driver scripts". Since Flask uses click for the scripts
157there is no reason you cannot hook these scripts into any click158application. There is one big caveat and that is, that commands159registered to :attr:`Flask.cli` will expect to be (indirectly at least)160launched from a :class:`flask.cli.FlaskGroup` click group. This is161necessary so that the commands know which Flask application they have to162work with.163164To understand why you might want custom scripts you need to understand how

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 165why, one step back
165click finds and executes the Flask application. If you use the :command:`flask`

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 166–181why, one step back
166script you specify the application to work with on the command line or
167environment variable as an import name. This is simple but it has some168limitations. Primarily it does not work with application factory169functions (see :ref:`app-factories`).170171With a custom script you don't have this problem as you can fully172customize how the application will be created. This is very useful if you173write reusable applications that you want to ship to users and they should174be presented with a custom management script.175176If you are used to writing click applications this will look familiar but177at the same time, slightly different because of how commands are loaded.178We won't go into detail now about the differences but if you are curious179you can have a look at the :ref:`script-info-object` section to learn all180about it.181

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 182why, one step back
182To explain all of this, here is an example :file:`manage.py` script that

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 183–225why, one step back
183manages a hypothetical wiki application. We will go through the details
184afterwards::185186 import click187 from flask.cli import FlaskGroup, script_info_option188189 def create_wiki_app(info):190 from yourwiki import create_app191 config = info.data.get('config') or 'wikiconfig.py'192 return create_app(config=config)193194 @click.group(cls=FlaskGroup, create_app=create_wiki_app)195 @script_info_option('--config', script_info_key='config')196 def cli(**params):197 """This is a management script for the wiki application."""198199 if __name__ == '__main__':200 cli()201202That's a lot of code for not much, so let's go through all parts step by203step.2042051. First we import the ``click`` library as well as the click extensions206 from the ``flask.cli`` package. Primarily we are here interested207 in the :class:`~flask.cli.FlaskGroup` click group and the208 :func:`~flask.cli.script_info_option` decorator.2092. The next thing we do is defining a function that is invoked with the210 script info object (:ref:`script-info-object`) from Flask and its211 purpose is to fully import and create the application. This can212 either directly import an application object or create it (see213 :ref:`app-factories`).214215 What is ``info.data``? It's a dictionary of arbitrary data on the216 script info that can be filled by options or through other means. We217 will come back to this later.2183. Next step is to create a :class:`FlaskGroup`. In this case we just219 make an empty function with a help doc string that just does nothing220 and then pass the ``create_wiki_app`` function as a factory function.221222 Whenever click now needs to operate on a Flask application it will223 call that function with the script info and ask for it to be created.2244. In step 2 you could see that the config is passed to the actual225 creation function. This config comes from the :func:`script_info_option`

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 226why, one step back
226 decorator for the main script. It accepts a :option:`--config` option and

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 227–241why, one step back
227 then stores it in the script info so we can use it to create the
228 application.2295. All is rounded up by invoking the script.230231.. _script-info-object:232233The Script Info234---------------235236The Flask script integration might be confusing at first, but there is a reason237why it's done this way. The reason for this is that Flask wants to238both provide custom commands to click as well as not loading your239application unless it has to. The reason for this is added flexibility.240241This way an application can provide custom commands, but even in the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 242why, one step back
242absence of an application the :command:`flask` script is still operational on a

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 243–255why, one step back
243basic level. In addition to that it means that the individual commands
244have the option to avoid creating an instance of the Flask application245unless required. This is very useful as it allows the server commands for246instance to load the application on a first request instead of247immediately, therefore giving a better debug experience.248249All of this is provided through the :class:`flask.cli.ScriptInfo` object250and some helper utilities around. The basic way it operates is that when251the :class:`flask.cli.FlaskGroup` executes as a script it creates a script252info and keeps it around. From that point onwards modifications on the253script info can be done through click options. To simplify this pattern254the :func:`flask.cli.script_info_option` decorator was added.255

Merge pull request #1263 from its-not-a-bug-its-a-feature/patch-1Markus Unterwaditzerbefore adoption924763a

line 256why, one step back
256Once Flask actually needs the individual Flask application it will invoke

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 257–259why, one step back
257the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the
258server starts, when the shell is launched or when the script looks for an259application-provided click command.