Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

659 lines · 19.0 KiB

Last changed by

Merge pull request #4343 from pallets/address-already-in-useDavid Lordbefore adoption776bf09

History of this file

Take it

1.. currentmodule:: flask23Command Line Interface4======================56Installing Flask installs the ``flask`` script, a `Click`_ command line7interface, in your virtualenv. Executed from the terminal, this script gives8access to built-in, extension, and application-defined commands. The ``--help``9option will give more information about any commands and options.1011.. _Click: https://click.palletsprojects.com/121314Application Discovery15---------------------1617The ``flask`` command is installed by Flask, not your application; it must be18told where to find your application in order to use it. The ``FLASK_APP``19environment variable is used to specify how to load the application.2021.. tabs::2223   .. group-tab:: Bash2425      .. code-block:: text2627         $ export FLASK_APP=hello28         $ flask run2930   .. group-tab:: CMD3132      .. code-block:: text3334         > set FLASK_APP=hello35         > flask run3637   .. group-tab:: Powershell3839      .. code-block:: text4041         > $env:FLASK_APP = "hello"42         > flask run4344While ``FLASK_APP`` supports a variety of options for specifying your45application, most use cases should be simple. Here are the typical values:4647(nothing)48    The name "app" or "wsgi" is imported (as a ".py" file, or package),49    automatically detecting an app (``app`` or ``application``) or50    factory (``create_app`` or ``make_app``).5152``FLASK_APP=hello``53    The given name is imported, automatically detecting an app (``app``54    or ``application``) or factory (``create_app`` or ``make_app``).5556----5758``FLASK_APP`` has three parts: an optional path that sets the current working59directory, a Python file or dotted import path, and an optional variable60name of the instance or factory. If the name is a factory, it can optionally61be followed by arguments in parentheses. The following values demonstrate these62parts:6364``FLASK_APP=src/hello``65    Sets the current working directory to ``src`` then imports ``hello``.6667``FLASK_APP=hello.web``68    Imports the path ``hello.web``.6970``FLASK_APP=hello:app2``71    Uses the ``app2`` Flask instance in ``hello``.7273``FLASK_APP="hello:create_app('dev')"``74    The ``create_app`` factory in ``hello`` is called with the string ``'dev'``75    as the argument.7677If ``FLASK_APP`` is not set, the command will try to import "app" or78"wsgi" (as a ".py" file, or package) and try to detect an application79instance or factory.8081Within the given import, the command looks for an application instance named82``app`` or ``application``, then any application instance. If no instance is83found, the command looks for a factory function named ``create_app`` or84``make_app`` that returns an instance.8586If parentheses follow the factory name, their contents are parsed as87Python literals and passed as arguments and keyword arguments to the88function. This means that strings must still be in quotes.899091Run the Development Server92--------------------------9394The :func:`run <cli.run_command>` command will start the development server. It95replaces the :meth:`Flask.run` method in most cases. ::9697    $ flask run98     * Serving Flask app "hello"99     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)100101.. warning:: Do not use this command to run your application in production.102    Only use the development server during development. The development server103    is provided for convenience, but is not designed to be particularly secure,104    stable, or efficient. See :doc:`/deploying/index` for how to run in production.105106If another program is already using port 5000, you'll see107``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the108server tries to start. See :ref:`address-already-in-use` for how to109handle that.110111112Open a Shell113------------114115To explore the data in your application, you can start an interactive Python116shell with the :func:`shell <cli.shell_command>` command. An application117context will be active, and the app instance will be imported. ::118119    $ flask shell120    Python 3.6.2 (default, Jul 20 2017, 03:52:27)121    [GCC 7.1.1 20170630] on linux122    App: example123    Instance: /home/user/Projects/hello/instance124    >>>125126Use :meth:`~Flask.shell_context_processor` to add other automatic imports.127128129Environments130------------131132.. versionadded:: 1.0133134The environment in which the Flask app runs is set by the135:envvar:`FLASK_ENV` environment variable. If not set it defaults to136``production``. The other recognized environment is ``development``.137Flask and extensions may choose to enable behaviors based on the138environment.139140If the env is set to ``development``, the ``flask`` command will enable141debug mode and ``flask run`` will enable the interactive debugger and142reloader.143144.. tabs::145146   .. group-tab:: Bash147148      .. code-block:: text149150         $ export FLASK_ENV=development151         $ flask run152          * Serving Flask app "hello"153          * Environment: development154          * Debug mode: on155          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)156          * Restarting with inotify reloader157          * Debugger is active!158          * Debugger PIN: 223-456-919159160   .. group-tab:: CMD161162      .. code-block:: text163164         > set FLASK_ENV=development165         > flask run166          * Serving Flask app "hello"167          * Environment: development168          * Debug mode: on169          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)170          * Restarting with inotify reloader171          * Debugger is active!172          * Debugger PIN: 223-456-919173174   .. group-tab:: Powershell175176      .. code-block:: text177178         > $env:FLASK_ENV = "development"179         > flask run180          * Serving Flask app "hello"181          * Environment: development182          * Debug mode: on183          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)184          * Restarting with inotify reloader185          * Debugger is active!186          * Debugger PIN: 223-456-919187188189Watch Extra Files with the Reloader190~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~191192When using development mode, the reloader will trigger whenever your193Python code or imported modules change. The reloader can watch194additional files with the ``--extra-files`` option, or the195``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are196separated with ``:``, or ``;`` on Windows.197198.. tabs::199200   .. group-tab:: Bash201202      .. code-block:: text203204          $ flask run --extra-files file1:dirA/file2:dirB/205          # or206          $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/207          $ flask run208           * Running on http://127.0.0.1:8000/209           * Detected change in '/path/to/file1', reloading210211   .. group-tab:: CMD212213      .. code-block:: text214215          > flask run --extra-files file1:dirA/file2:dirB/216          # or217          > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/218          > flask run219           * Running on http://127.0.0.1:8000/220           * Detected change in '/path/to/file1', reloading221222   .. group-tab:: Powershell223224      .. code-block:: text225226          > flask run --extra-files file1:dirA/file2:dirB/227          # or228          > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"229          > flask run230           * Running on http://127.0.0.1:8000/231           * Detected change in '/path/to/file1', reloading232233234Debug Mode235----------236237Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,238as described above. If you want to control debug mode separately, use239:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.240241242.. _dotenv:243244Environment Variables From dotenv245---------------------------------246247Rather than setting ``FLASK_APP`` each time you open a new terminal, you can248use Flask's dotenv support to set environment variables automatically.249250If `python-dotenv`_ is installed, running the ``flask`` command will set251environment variables defined in the files :file:`.env` and :file:`.flaskenv`.252This can be used to avoid having to set ``FLASK_APP`` manually every time you253open a new terminal, and to set configuration using environment variables254similar to how some deployment services work.255256Variables set on the command line are used over those set in :file:`.env`,257which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be258used for public variables, such as ``FLASK_APP``, while :file:`.env` should not259be committed to your repository so that it can set private variables.260261Directories are scanned upwards from the directory you call ``flask``262from to locate the files. The current working directory will be set to the263location of the file, with the assumption that that is the top level project264directory.265266The files are only loaded by the ``flask`` command or calling267:meth:`~Flask.run`. If you would like to load these files when running in268production, you should call :func:`~cli.load_dotenv` manually.269270.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme271272273Setting Command Options274~~~~~~~~~~~~~~~~~~~~~~~275276Click is configured to load default values for command options from277environment variables. The variables use the pattern278``FLASK_COMMAND_OPTION``. For example, to set the port for the run279command, instead of ``flask run --port 8000``:280281.. tabs::282283   .. group-tab:: Bash284285      .. code-block:: text286287         $ export FLASK_RUN_PORT=8000288         $ flask run289          * Running on http://127.0.0.1:8000/290291   .. group-tab:: CMD292293      .. code-block:: text294295         > set FLASK_RUN_PORT=8000296         > flask run297          * Running on http://127.0.0.1:8000/298299   .. group-tab:: Powershell300301      .. code-block:: text302303         > $env:FLASK_RUN_PORT = 8000304         > flask run305          * Running on http://127.0.0.1:8000/306307These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to308control default command options.309310311Disable dotenv312~~~~~~~~~~~~~~313314The ``flask`` command will show a message if it detects dotenv files but315python-dotenv is not installed.316317.. code-block:: bash318319    $ flask run320     * Tip: There are .env files present. Do "pip install python-dotenv" to use them.321322You can tell Flask not to load dotenv files even when python-dotenv is323installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.324This can be useful if you want to load them manually, or if you're using325a project runner that loads them already. Keep in mind that the326environment variables must be set before the app loads or it won't327configure as expected.328329.. tabs::330331   .. group-tab:: Bash332333      .. code-block:: text334335         $ export FLASK_SKIP_DOTENV=1336         $ flask run337338   .. group-tab:: CMD339340      .. code-block:: text341342         > set FLASK_SKIP_DOTENV=1343         > flask run344345   .. group-tab:: Powershell346347      .. code-block:: text348349         > $env:FLASK_SKIP_DOTENV = 1350         > flask run351352353Environment Variables From virtualenv354-------------------------------------355356If you do not want to install dotenv support, you can still set environment357variables by adding them to the end of the virtualenv's :file:`activate`358script. Activating the virtualenv will set the variables.359360.. tabs::361362   .. group-tab:: Bash363364      Unix Bash, :file:`venv/bin/activate`::365366          $ export FLASK_APP=hello367368   .. group-tab:: CMD369370      Windows CMD, :file:`venv\\Scripts\\activate.bat`::371372          > set FLASK_APP=hello373374   .. group-tab:: Powershell375376      Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::377378          > $env:FLASK_APP = "hello"379380It is preferred to use dotenv support over this, since :file:`.flaskenv` can be381committed to the repository so that it works automatically wherever the project382is checked out.383384385Custom Commands386---------------387388The ``flask`` command is implemented using `Click`_. See that project's389documentation for full information about writing commands.390391This example adds the command ``create-user`` that takes the argument392``name``. ::393394    import click395    from flask import Flask396397    app = Flask(__name__)398399    @app.cli.command("create-user")400    @click.argument("name")401    def create_user(name):402        ...403404::405406    $ flask create-user admin407408This example adds the same command, but as ``user create``, a command in a409group. This is useful if you want to organize multiple related commands. ::410411    import click412    from flask import Flask413    from flask.cli import AppGroup414415    app = Flask(__name__)416    user_cli = AppGroup('user')417418    @user_cli.command('create')419    @click.argument('name')420    def create_user(name):421        ...422423    app.cli.add_command(user_cli)424425::426427    $ flask user create demo428429See :ref:`testing-cli` for an overview of how to test your custom430commands.431432433Registering Commands with Blueprints434~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~435436If your application uses blueprints, you can optionally register CLI437commands directly onto them. When your blueprint is registered onto your438application, the associated commands will be available to the ``flask``439command. By default, those commands will be nested in a group matching440the name of the blueprint.441442.. code-block:: python443444    from flask import Blueprint445446    bp = Blueprint('students', __name__)447448    @bp.cli.command('create')449    @click.argument('name')450    def create(name):451        ...452453    app.register_blueprint(bp)454455.. code-block:: text456457    $ flask students create alice458459You can alter the group name by specifying the ``cli_group`` parameter460when creating the :class:`Blueprint` object, or later with461:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.462The following are equivalent:463464.. code-block:: python465466    bp = Blueprint('students', __name__, cli_group='other')467    # or468    app.register_blueprint(bp, cli_group='other')469470.. code-block:: text471472    $ flask other create alice473474Specifying ``cli_group=None`` will remove the nesting and merge the475commands directly to the application's level:476477.. code-block:: python478479    bp = Blueprint('students', __name__, cli_group=None)480    # or481    app.register_blueprint(bp, cli_group=None)482483.. code-block:: text484485    $ flask create alice486487488Application Context489~~~~~~~~~~~~~~~~~~~490491Commands added using the Flask app's :attr:`~Flask.cli`492:meth:`~cli.AppGroup.command` decorator will be executed with an application493context pushed, so your command and extensions have access to the app and its494configuration. If you create a command using the Click :func:`~click.command`495decorator instead of the Flask decorator, you can use496:func:`~cli.with_appcontext` to get the same behavior. ::497498    import click499    from flask.cli import with_appcontext500501    @click.command()502    @with_appcontext503    def do_work():504        ...505506    app.cli.add_command(do_work)507508If you're sure a command doesn't need the context, you can disable it::509510    @app.cli.command(with_appcontext=False)511    def do_work():512        ...513514515Plugins516-------517518Flask will automatically load commands specified in the ``flask.commands``519`entry point`_. This is useful for extensions that want to add commands when520they are installed. Entry points are specified in :file:`setup.py` ::521522    from setuptools import setup523524    setup(525        name='flask-my-extension',526        ...,527        entry_points={528            'flask.commands': [529                'my-command=flask_my_extension.commands:cli'530            ],531        },532    )533534535.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points536537Inside :file:`flask_my_extension/commands.py` you can then export a Click538object::539540    import click541542    @click.command()543    def cli():544        ...545546Once that package is installed in the same virtualenv as your Flask project,547you can run ``flask my-command`` to invoke the command.548549550.. _custom-scripts:551552Custom Scripts553--------------554555When you are using the app factory pattern, it may be more convenient to define556your own Click script. Instead of using ``FLASK_APP`` and letting Flask load557your application, you can create your own Click object and export it as a558`console script`_ entry point.559560Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::561562    import click563    from flask import Flask564    from flask.cli import FlaskGroup565566    def create_app():567        app = Flask('wiki')568        # other setup569        return app570571    @click.group(cls=FlaskGroup, create_app=create_app)572    def cli():573        """Management script for the Wiki application."""574575Define the entry point in :file:`setup.py`::576577    from setuptools import setup578579    setup(580        name='flask-my-extension',581        ...,582        entry_points={583            'console_scripts': [584                'wiki=wiki:cli'585            ],586        },587    )588589Install the application in the virtualenv in editable mode and the custom590script is available. Note that you don't need to set ``FLASK_APP``. ::591592    $ pip install -e .593    $ wiki run594595.. admonition:: Errors in Custom Scripts596597    When using a custom script, if you introduce an error in your598    module-level code, the reloader will fail because it can no longer599    load the entry point.600601    The ``flask`` command, being separate from your code, does not have602    this issue and is recommended in most cases.603604.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts605606607PyCharm Integration608-------------------609610PyCharm Professional provides a special Flask run configuration. For611the Community Edition, we need to configure it to call the ``flask run``612CLI command with the correct environment variables. These instructions613should be similar for any other IDE you might want to use.614615In PyCharm, with your project open, click on *Run* from the menu bar and616go to *Edit Configurations*. You'll be greeted by a screen similar to617this:618619.. image:: _static/pycharm-runconfig.png620    :align: center621    :class: screenshot622    :alt: Screenshot of PyCharms's run configuration settings.623624There's quite a few options to change, but once we've done it for one625command, we can easily copy the entire configuration and make a single626tweak to give us access to other commands, including any custom ones you627may implement yourself.628629Click the + (*Add New Configuration*) button and select *Python*. Give630the configuration a name such as "flask run". For the ``flask run``631command, check "Single instance only" since you can't run the server632more than once at the same time.633634Select *Module name* from the dropdown (**A**) then input ``flask``.635636The *Parameters* field (**B**) is set to the CLI command to execute637(with any arguments). In this example we use ``run``, which will run638the development server.639640You can skip this next step if you're using :ref:`dotenv`. We need to641add an environment variable (**C**) to identify our application. Click642on the browse button and add an entry with ``FLASK_APP`` on the left and643the Python import or file on the right (``hello`` for example). Add an644entry with ``FLASK_ENV`` and set it to ``development``.645646Next we need to set the working directory (**D**) to be the folder where647our application resides.648649If you have installed your project as a package in your virtualenv, you650may untick the *PYTHONPATH* options (**E**). This will more accurately651match how you deploy the app later.652653Click *Apply* to save the configuration, or *OK* to save and close the654window. Select the configuration in the main PyCharm window and click655the play button next to it to run the server.656657Now that we have a configuration which runs ``flask run`` from within658PyCharm, we can copy that configuration and alter the *Script* argument659to run a different CLI command, e.g. ``flask shell``.