cli.rst
This file
Path
docs/cli.rst
303 lines · 10.8 KiB
Last changed by
Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
History of this fileTake it
The walk stopped after 200 commits: lines older than 7df543d point at it.
Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 1–5why, one step back1.. _cli:23Command Line Interface4======================5s/1.0/0.11/ in versionadded/versionchanged markersThiefMasterbefore adoptionc5900a1
line 6why, one step back6.. versionadded:: 0.11Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 7–9why, one step back78.. currentmodule:: flask91.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe
line 10why, one step back10One of the nice new features in Flask 0.11 is the built-in integration ofMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 11–17why, one step back11the `click <http://click.pocoo.org/>`_ command line interface. This12enables a wide range of new features for the Flask ecosystem and your own13applications.1415Basic Usage16-----------17Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 18–21why, one step back18After installation of Flask you will now find a :command:`flask` script19installed into your virtualenv. If you don't want to install Flask or you20have a special use-case you can also use ``python -m flask`` to accomplish21exactly the same.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 22–27why, one step back2223The 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.27Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 28–31why, one step back28For the :command:`flask` script to work, an application needs to be29discovered. This is achieved by exporting the ``FLASK_APP`` environment30variable. It can be either set to an import path or to a filename of a31Python module that contains a Flask application.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 32–33why, one step back3233In that imported file the name of the app needs to be called ``app`` orUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 34why, one step back34optionally be specified after a colon. For instanceclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 35why, one step back35``mymodule:application`` would tell it to use the `application` object inUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 36why, one step back36the :file:`mymodule.py` file.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 37why, one step back37Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 38–39why, one step back38Given a :file:`hello.py` file with the application in it named ``app``39this is how it can be run.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 40–45why, one step back4041Environment variables (On Windows use ``set`` instead of ``export``)::4243 export FLASK_APP=hello44 flask run45Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 46why, one step back46Or with a filename::Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 47why, one step back47Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 48–49why, one step back48 export FLASK_APP=/path/to/hello.py49 flask runMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 50–58why, one step back5051Virtualenv Integration52----------------------5354If you are constantly working with a virtualenv you can also put the55``export FLASK_APP`` into your ``activate`` script by adding it to the56bottom of the file. That way every time you activate your virtualenv you57automatically also activate the correct application name.58Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 59–70why, one step back59Edit the activate script for the shell you use. For example:6061Unix Bash: ``venv/bin/activate``::6263 FLASK_APP=hello64 export FLASK_APP6566Windows CMD.exe: ``venv\Scripts\activate.bat``::6768 set "FLASK_APP=hello"69 :END70Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 71–73why, one step back71Debug Flag72----------73Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 74–75why, one step back74The :command:`flask` script can also be instructed to enable the debug75mode of the application automatically by exporting ``FLASK_DEBUG``. IfRemove nonsense from cli docsAndrew Arendtbefore adoption270355a
line 76why, one step back76set to ``1`` debug is enabled or ``0`` disables it::Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 77–79why, one step back7778 export FLASK_DEBUG=179Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 80–84why, one step back80Running a Shell81---------------8283To run an interactive Python shell you can use the ``shell`` command::84Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 85why, one step back85 flask shellMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 86–99why, one step back8687This will start up an interactive Python shell, setup the correct88application context and setup the local variables in the shell. This is89done by invoking the :meth:`Flask.make_shell_context` method of the90application. By default you have access to your ``app`` and :data:`g`.9192Custom Commands93---------------9495If you want to add more commands to the shell script you can do this96easily. Flask uses `click`_ for the command interface which makes97creating custom commands very easy. For instance if you want a shell98command to initialize the database you can do this::99Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 100why, one step back100 import clickMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 101–107why, one step back101 from flask import Flask102103 app = Flask(__name__)104105 @app.cli.command()106 def initdb():107 """Initialize the database."""Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 108why, one step back108 click.echo('Init the db')Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 109–111why, one step back109110The command will then show up on the command line::111Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 112why, one step back112 $ flask initdbMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 113–136why, one step back113 Init the db114115Application Context116-------------------117118Most commands operate on the application so it makes a lot of sense if119they have the application context setup. Because of this, if you register120a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the121callback will automatically be wrapped through :func:`cli.with_appcontext`122which informs the cli system to ensure that an application context is set123up. This behavior is not available if a command is added later with124:func:`~click.Group.add_command` or through other means.125126It can also be disabled by passing ``with_appcontext=False`` to the127decorator::128129 @app.cli.command(with_appcontext=False)130 def example():131 pass132133Factory Functions134-----------------135136In case you are using factory functions to create your application (seeUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 137–138why, one step back137:ref:`app-factories`) you will discover that the :command:`flask` command138cannot work with them directly. Flask won't be able to figure out how toMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 139–140why, one step back139instantiate your application properly by itself. Because of this reason140the recommendation is to create a separate file that instantiatesUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 141–142why, one step back141applications. This is not the only way to make this work. Another is the142:ref:`custom-scripts` support.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 143–153why, one step back143144For instance if you have a factory function that creates an application145from a filename you could make a separate file that creates such an146application from an environment variable.147148This could be a file named :file:`autoapp.py` with these contents::149150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153Style the flask command consistently (#2120)Sven-Hendrik Haasebefore adoption0ba1a87
lines 154–155why, one step back154Once this has happened you can make the :command:`flask` command automatically155pick it up::Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 156–166why, one step back156157 export YOURAPPLICATION_CONFIG=/path/to/config.cfg158 export FLASK_APP=/path/to/autoapp.py159160From this point onwards :command:`flask` will find your application.161162.. _custom-scripts:163164Custom Scripts165--------------166Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 167–169why, one step back167While the most common way is to use the :command:`flask` command, you can168also make your own "driver scripts". Since Flask uses click for the169scripts there is no reason you cannot hook these scripts into any clickMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 170–176why, one step back170application. There is one big caveat and that is, that commands171registered to :attr:`Flask.cli` will expect to be (indirectly at least)172launched from a :class:`flask.cli.FlaskGroup` click group. This is173necessary so that the commands know which Flask application they have to174work with.175176To understand why you might want custom scripts you need to understand howUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 177–181why, one step back177click finds and executes the Flask application. If you use the178:command:`flask` script you specify the application to work with on the179command line or environment variable as an import name. This is simple180but it has some limitations. Primarily it does not work with application181factory functions (see :ref:`app-factories`).Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 182–191why, one step back182183With a custom script you don't have this problem as you can fully184customize how the application will be created. This is very useful if you185write reusable applications that you want to ship to users and they should186be presented with a custom management script.187188To explain all of this, here is an example :file:`manage.py` script that189manages a hypothetical wiki application. We will go through the details190afterwards::191Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 192why, one step back192 import osMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 193why, one step back193 import clickUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 194why, one step back194 from flask.cli import FlaskGroupMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 195–197why, one step back195196 def create_wiki_app(info):197 from yourwiki import create_appUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 198–199why, one step back198 return create_app(199 config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 200–201why, one step back200201 @click.group(cls=FlaskGroup, create_app=create_wiki_app)Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 202why, one step back202 def cli():Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 203–212why, one step back203 """This is a management script for the wiki application."""204205 if __name__ == '__main__':206 cli()207208That's a lot of code for not much, so let's go through all parts step by209step.2102111. First we import the ``click`` library as well as the click extensions212 from the ``flask.cli`` package. Primarily we are here interestedUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 213why, one step back213 in the :class:`~flask.cli.FlaskGroup` click group.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 214why, one step back2142. The next thing we do is defining a function that is invoked with theUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 215why, one step back215 script info object (:class:`~flask.cli.ScriptInfo`) from Flask and itsMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 216–217why, one step back216 purpose is to fully import and create the application. This can217 either directly import an application object or create it (seeUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 218–219why, one step back218 :ref:`app-factories`). In this case we load the config from an219 environment variable.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 220–225why, one step back2203. Next step is to create a :class:`FlaskGroup`. In this case we just221 make an empty function with a help doc string that just does nothing222 and then pass the ``create_wiki_app`` function as a factory function.223224 Whenever click now needs to operate on a Flask application it will225 call that function with the script info and ask for it to be created.Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 226why, one step back2264. All is rounded up by invoking the script.Merge pull request #1821 from pallets/feature/plugin-cliArmin Ronacherbefore adoptionc73cf0f
lines 227–230why, one step back227228CLI Plugins229-----------230clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 231why, one step back231Flask extensions can always patch the :attr:`Flask.cli` instance with moreMerge pull request #1821 from pallets/feature/plugin-cliArmin Ronacherbefore adoptionc73cf0f
line 232why, one step back232commands if they want. However there is a second way to add CLI pluginsclean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 233–234why, one step back233to Flask which is through ``setuptools``. If you make a Python package that234should export a Flask command line plugin you can ship a :file:`setup.py` fileMerge pull request #1821 from pallets/feature/plugin-cliArmin Ronacherbefore adoptionc73cf0f
lines 235–236why, one step back235that declares an entrypoint that points to a click command:236clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 237why, one step back237Example :file:`setup.py`::Merge pull request #1821 from pallets/feature/plugin-cliArmin Ronacherbefore adoptionc73cf0f
lines 238–249why, one step back238239 from setuptools import setup240241 setup(242 name='flask-my-extension',243 ...244 entry_points='''245 [flask.commands]246 my-command=mypackage.commands:cli247 ''',248 )249clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 250why, one step back250Inside :file:`mypackage/commands.py` you can then export a Click object::Merge pull request #1821 from pallets/feature/plugin-cliArmin Ronacherbefore adoptionc73cf0f
lines 251–260why, one step back251252 import click253254 @click.command()255 def cli():256 """This is an example command."""257258Once that package is installed in the same virtualenv as Flask itself you259can run ``flask my-command`` to invoke your command. This is useful to260provide extra functionality that Flask itself cannot ship.Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 261–303why, one step back261262PyCharm Integration263-------------------264265The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,266so we have to do a few tweaks to get them working smoothly.267268In your PyCharm application, with your project open, click on *Run*269from the menu bar and go to *Edit Configurations*. You’ll be greeted by a270screen similar to this:271272.. image:: _static/pycharm-runconfig.png273 :align: center274 :class: screenshot275 :alt: screenshot of pycharm's run configuration settings276277There’s quite a few options to change, but don’t worry— once we’ve done it278for one command, we can easily copy the entire configuration and make a279single tweak to give us access to other flask cli commands, including280any custom ones you may implement yourself.281282For the *Script* input (**A**), we want to navigate to the virtual environment283we’re using for our project and within that folder we want to pick the ``flask``284file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if285you're on Windows.286287The *Script Parameter* field (**B**) is set to the cli command you wish to288execute, in this example we use ``run`` which will run our development server.289290We need to add an environment variable (**C**) to identify our application.291Click on the browse button and add an entry with ``FLASK_APP`` on the292left and the name of the python file, or package on the right293(``app.py`` for example).294295Next we need to set the working directory (**D**) to be the same folder where296our application file or package resides.297298Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a299good descriptive name, such as “Run Flask Server” and click *Apply*.300301Now that we have on run configuration which implements ``flask run`` from within302PyCharm, we can simply copy that configuration and alter the script argument303to run a different cli command, e.g. ``flask shell``.