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 fileTake it
The walk stopped after 200 commits: lines older than 5693b9d point at it.
Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 1–17why, one step back1.. _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-----------17Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 18why, one step back18After installation of Flask you will now find a :command:`flask` script installedMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
line 19why, one step back19into your virtualenv. If you don't want to install Flask or you have aMerge pull request #1057 from IanConnolly/doc-fixKenneth Reitzbefore adoptionda1c1f0
line 20why, one step back20special use-case you can also use ``python -m flask`` to accomplish exactlyMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 21–25why, one step back21the 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 alsoMerge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
line 26why, one step back26register more commands there if they desire so.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
line 27why, one step back27Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 28why, one step back28For the :command:`flask` script to work, an application needs to be discovered.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
line 29why, one step back29The two most common ways are either an environment variableMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 30why, one step back30(``FLASK_APP``) or the :option:`--app` / :option:`-a` parameter. It should be theMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 31–37why, one step back31import path for your application or the path to a Python file. In the32latter 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.37Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 38why, one step back38Given a :file:`hello.py` file with the application in it named ``app`` this isMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 39–64why, one step back39how 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----------64Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 65why, one step back65The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` toMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 66–102why, one step back66automatically flip the debug flag of the application. This can also be67configured 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 db102Refactored the scripting interface greatly.Armin Ronacherbefore adoption932f7d7
lines 103–110why, one step back103Application 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 setMerge pull request #1217 from jeffwidman/patch-1Markus Unterwaditzerbefore adoption7b3e52b
line 111why, one step back111up. This behavior is not available if a command is added later withRefactored the scripting interface greatly.Armin Ronacherbefore adoption932f7d7
lines 112–120why, one step back112: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 pass120Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 121–124why, one step back121Factory Functions122-----------------123124In case you are using factory functions to create your application (seeMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 125why, one step back125:ref:`app-factories`) you will discover that the :command:`flask` command cannotMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
line 126why, one step back126work with them directly. Flask won't be able to figure out how toMerge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
lines 127–128why, one step back127instantiate your application properly by itself. Because of this reason128the recommendation is to create a separate file that instantiatesMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 129–135why, one step back129applications. 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.135Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 136why, one step back136This could be a file named :file:`autoapp.py` with these contents::Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 137–147why, one step back137138 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.py147Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 148why, one step back148From this point onwards :command:`flask` will find your application.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 149–154why, one step back149150.. _custom-scripts:151152Custom Scripts153--------------154Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 155why, one step back155While the most common way is to use the :command:`flask` command, you can alsoMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 156–164why, one step back156make your own "driver scripts". Since Flask uses click for the scripts157there 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 howMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 165why, one step back165click finds and executes the Flask application. If you use the :command:`flask`Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 166–181why, one step back166script you specify the application to work with on the command line or167environment 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.181Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 182why, one step back182To explain all of this, here is an example :file:`manage.py` script thatMerge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
line 183why, one step back183manages a hypothetical wiki application. We will go through the detailsMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 184–204why, one step back184afterwards::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.204Merge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
line 205why, one step back2051. First we import the ``click`` library as well as the click extensionsMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 206–209why, one step back206 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 theMerge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
line 210why, one step back210 script info object (:ref:`script-info-object`) from Flask and itsMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 211–214why, one step back211 purpose is to fully import and create the application. This can212 either directly import an application object or create it (see213 :ref:`app-factories`).214Merge pull request #1105 from limeburst/masterKenneth Reitzbefore adoption5775816
line 215why, one step back215 What is ``info.data``? It's a dictionary of arbitrary data on theMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 216–219why, one step back216 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 nothingMerge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
line 220why, one step back220 and then pass the ``create_wiki_app`` function as a factory function.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
line 221why, one step back221Merge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
line 222why, one step back222 Whenever click now needs to operate on a Flask application it willMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 223–225why, one step back223 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 back226 decorator for the main script. It accepts a :option:`--config` option andMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 227–235why, one step back227 then stores it in the script info so we can use it to create the228 application.2295. All is rounded up by invoking the script.230231.. _script-info-object:232233The Script Info234---------------235Merge pull request #1057 from IanConnolly/doc-fixKenneth Reitzbefore adoptionda1c1f0
lines 236–237why, one step back236The 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 toMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 238–241why, one step back238both 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 theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 242why, one step back242absence of an application the :command:`flask` script is still operational on aMerge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
lines 243–247why, one step back243basic level. In addition to that it means that the individual commands244have 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.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 248–255why, one step back248249All 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.255Merge pull request #1263 from its-not-a-bug-its-a-feature/patch-1Markus Unterwaditzerbefore adoption924763a
line 256why, one step back256Once Flask actually needs the individual Flask application it will invokeMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 257–258why, one step back257the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the258server starts, when the shell is launched or when the script looks for anMerge pull request #1050 from julen/doc-fixesKenneth Reitzbefore adoption32d3224
line 259why, one step back259application-provided click command.