Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

307 lines · 11.0 KiB

Last changed by

Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a

History of this file

Take it

1.. _cli:23Command Line Interface4======================56.. versionadded:: 0.1178.. currentmodule:: flask910One of the nice new features in Flask 0.11 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-----------1718After 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.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.2728For the :command:`flask` script to work, an application needs to be discovered.29Flask looks for a module named :file:`wsgi.py` or :file:`app.py` by default,30and if it finds one it assumes the application is defined in it.3132You can instruct Flask to look for the application in a different module by33exporting the ``FLASK_APP`` environment variable. It can be either set to an34import path or to a filename of a Python module that contains a Flask35application.3637In that imported file the name of the app needs to be called ``app`` or38optionally be specified after a colon.  For instance39``mymodule:application`` would tell it to use the `application` object in40the :file:`mymodule.py` file.4142Given a :file:`hello.py` file with the application in it named ``app``43this is how it can be run.4445Environment variables (On Windows use ``set`` instead of ``export``)::4647    export FLASK_APP=hello48    flask run4950Or with a filename::5152    export FLASK_APP=/path/to/hello.py53    flask run5455Virtualenv Integration56----------------------5758If you are constantly working with a virtualenv you can also put the59``export FLASK_APP`` into your ``activate`` script by adding it to the60bottom of the file.  That way every time you activate your virtualenv you61automatically also activate the correct application name.6263Edit the activate script for the shell you use. For example:6465Unix Bash: ``venv/bin/activate``::6667    FLASK_APP=hello68    export FLASK_APP6970Windows CMD.exe: ``venv\Scripts\activate.bat``::7172    set "FLASK_APP=hello"73    :END7475Debug Flag76----------7778The :command:`flask` script can also be instructed to enable the debug79mode of the application automatically by exporting ``FLASK_DEBUG``.  If80set to ``1`` debug is enabled or ``0`` disables it::8182    export FLASK_DEBUG=18384Running a Shell85---------------8687To run an interactive Python shell you can use the ``shell`` command::8889    flask shell9091This will start up an interactive Python shell, setup the correct92application context and setup the local variables in the shell.  This is93done by invoking the :meth:`Flask.make_shell_context` method of the94application.  By default you have access to your ``app`` and :data:`g`.9596Custom Commands97---------------9899If you want to add more commands to the shell script you can do this100easily.  Flask uses `click`_ for the command interface which makes101creating custom commands very easy.  For instance if you want a shell102command to initialize the database you can do this::103104    import click105    from flask import Flask106107    app = Flask(__name__)108109    @app.cli.command()110    def initdb():111        """Initialize the database."""112        click.echo('Init the db')113114The command will then show up on the command line::115116    $ flask initdb117    Init the db118119Application Context120-------------------121122Most commands operate on the application so it makes a lot of sense if123they have the application context setup.  Because of this, if you register124a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the125callback will automatically be wrapped through :func:`cli.with_appcontext`126which informs the cli system to ensure that an application context is set127up.  This behavior is not available if a command is added later with128:func:`~click.Group.add_command` or through other means.129130It can also be disabled by passing ``with_appcontext=False`` to the131decorator::132133    @app.cli.command(with_appcontext=False)134    def example():135        pass136137Factory Functions138-----------------139140In case you are using factory functions to create your application (see141:ref:`app-factories`) you will discover that the :command:`flask` command142cannot work with them directly.  Flask won't be able to figure out how to143instantiate your application properly by itself.  Because of this reason144the recommendation is to create a separate file that instantiates145applications.  This is not the only way to make this work.  Another is the146:ref:`custom-scripts` support.147148For instance if you have a factory function that creates an application149from a filename you could make a separate file that creates such an150application from an environment variable.151152This could be a file named :file:`autoapp.py` with these contents::153154    import os155    from yourapplication import create_app156    app = create_app(os.environ['YOURAPPLICATION_CONFIG'])157158Once this has happened you can make the :command:`flask` command automatically159pick it up::160161    export YOURAPPLICATION_CONFIG=/path/to/config.cfg162    export FLASK_APP=/path/to/autoapp.py163164From this point onwards :command:`flask` will find your application.165166.. _custom-scripts:167168Custom Scripts169--------------170171While the most common way is to use the :command:`flask` command, you can172also make your own "driver scripts".  Since Flask uses click for the173scripts there is no reason you cannot hook these scripts into any click174application.  There is one big caveat and that is, that commands175registered to :attr:`Flask.cli` will expect to be (indirectly at least)176launched from a :class:`flask.cli.FlaskGroup` click group.  This is177necessary so that the commands know which Flask application they have to178work with.179180To understand why you might want custom scripts you need to understand how181click finds and executes the Flask application.  If you use the182:command:`flask` script you specify the application to work with on the183command line or environment variable as an import name.  This is simple184but it has some limitations.  Primarily it does not work with application185factory functions (see :ref:`app-factories`).186187With a custom script you don't have this problem as you can fully188customize how the application will be created.  This is very useful if you189write reusable applications that you want to ship to users and they should190be presented with a custom management script.191192To explain all of this, here is an example :file:`manage.py` script that193manages a hypothetical wiki application.  We will go through the details194afterwards::195196    import os197    import click198    from flask.cli import FlaskGroup199200    def create_wiki_app(info):201        from yourwiki import create_app202        return create_app(203            config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))204205    @click.group(cls=FlaskGroup, create_app=create_wiki_app)206    def cli():207        """This is a management script for the wiki application."""208209    if __name__ == '__main__':210        cli()211212That's a lot of code for not much, so let's go through all parts step by213step.2142151.  First we import the ``click`` library as well as the click extensions216    from the ``flask.cli`` package.  Primarily we are here interested217    in the :class:`~flask.cli.FlaskGroup` click group.2182.  The next thing we do is defining a function that is invoked with the219    script info object (:class:`~flask.cli.ScriptInfo`) from Flask and its220    purpose is to fully import and create the application.  This can221    either directly import an application object or create it (see222    :ref:`app-factories`).  In this case we load the config from an223    environment variable.2243.  Next step is to create a :class:`FlaskGroup`.  In this case we just225    make an empty function with a help doc string that just does nothing226    and then pass the ``create_wiki_app`` function as a factory function.227228    Whenever click now needs to operate on a Flask application it will229    call that function with the script info and ask for it to be created.2304.  All is rounded up by invoking the script.231232CLI Plugins233-----------234235Flask extensions can always patch the :attr:`Flask.cli` instance with more236commands if they want.  However there is a second way to add CLI plugins237to Flask which is through ``setuptools``.  If you make a Python package that238should export a Flask command line plugin you can ship a :file:`setup.py` file239that declares an entrypoint that points to a click command:240241Example :file:`setup.py`::242243    from setuptools import setup244245    setup(246        name='flask-my-extension',247        ...248        entry_points='''249            [flask.commands]250            my-command=mypackage.commands:cli251        ''',252    )253254Inside :file:`mypackage/commands.py` you can then export a Click object::255256    import click257258    @click.command()259    def cli():260        """This is an example command."""261262Once that package is installed in the same virtualenv as Flask itself you263can run ``flask my-command`` to invoke your command.  This is useful to264provide extra functionality that Flask itself cannot ship.265266PyCharm Integration267-------------------268269The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,270so we have to do a few tweaks to get them working smoothly.271272In your PyCharm application, with your project open, click on *Run*273from the menu bar and go to *Edit Configurations*. You’ll be greeted by a274screen similar to this:275276.. image:: _static/pycharm-runconfig.png277   :align: center278   :class: screenshot279   :alt: screenshot of pycharm's run configuration settings280281There’s quite a few options to change, but don’t worry— once we’ve done it282for one command, we can easily copy the entire configuration and make a283single tweak to give us access to other flask cli commands, including284any custom ones you may implement yourself.285286For the *Script* input (**A**), we want to navigate to the virtual environment287we’re using for our project and within that folder we want to pick the ``flask``288file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if289you're on Windows.290291The *Script Parameter* field (**B**) is set to the cli command you wish to292execute, in this example we use ``run`` which will run our development server.293294We need to add an environment variable (**C**) to identify our application.295Click on the browse button and add an entry with ``FLASK_APP`` on the296left and the name of the python file, or package on the right297(``app.py`` for example).298299Next we need to set the working directory (**D**) to be the same folder where300our application file or package resides.301302Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a303good descriptive name, such as “Run Flask Server” and click *Apply*.304305Now that we have on run configuration which implements ``flask run`` from within306PyCharm, we can simply copy that configuration and alter the script argument307to run a different cli command, e.g. ``flask shell``.