Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

604 lines · 17.7 KiB

Last changed by

Merge pull request #4647 from pallets/cli-app_contextDavid Lordbefore adoptioncec5f74

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 ``--app``19option is used to specify how to load the application.2021While ``--app`` supports a variety of options for specifying your22application, most use cases should be simple. Here are the typical values:2324(nothing)25    The name "app" or "wsgi" is imported (as a ".py" file, or package),26    automatically detecting an app (``app`` or ``application``) or27    factory (``create_app`` or ``make_app``).2829``--app hello``30    The given name is imported, automatically detecting an app (``app``31    or ``application``) or factory (``create_app`` or ``make_app``).3233----3435``--app`` has three parts: an optional path that sets the current working36directory, a Python file or dotted import path, and an optional variable37name of the instance or factory. If the name is a factory, it can optionally38be followed by arguments in parentheses. The following values demonstrate these39parts:4041``--app src/hello``42    Sets the current working directory to ``src`` then imports ``hello``.4344``--app hello.web``45    Imports the path ``hello.web``.4647``--app hello:app2``48    Uses the ``app2`` Flask instance in ``hello``.4950``--app 'hello:create_app("dev")'``51    The ``create_app`` factory in ``hello`` is called with the string ``'dev'``52    as the argument.5354If ``--app`` is not set, the command will try to import "app" or55"wsgi" (as a ".py" file, or package) and try to detect an application56instance or factory.5758Within the given import, the command looks for an application instance named59``app`` or ``application``, then any application instance. If no instance is60found, the command looks for a factory function named ``create_app`` or61``make_app`` that returns an instance.6263If parentheses follow the factory name, their contents are parsed as64Python literals and passed as arguments and keyword arguments to the65function. This means that strings must still be in quotes.666768Run the Development Server69--------------------------7071The :func:`run <cli.run_command>` command will start the development server. It72replaces the :meth:`Flask.run` method in most cases. ::7374    $ flask run75     * Serving Flask app "hello"76     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)7778.. warning:: Do not use this command to run your application in production.79    Only use the development server during development. The development server80    is provided for convenience, but is not designed to be particularly secure,81    stable, or efficient. See :doc:`/deploying/index` for how to run in production.8283If another program is already using port 5000, you'll see84``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the85server tries to start. See :ref:`address-already-in-use` for how to86handle that.878889Open a Shell90------------9192To explore the data in your application, you can start an interactive Python93shell with the :func:`shell <cli.shell_command>` command. An application94context will be active, and the app instance will be imported. ::9596    $ flask shell97    Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux98    App: example [production]99    Instance: /home/david/Projects/pallets/flask/instance100    >>>101102Use :meth:`~Flask.shell_context_processor` to add other automatic imports.103104105Environments106------------107108.. versionadded:: 1.0109110The environment in which the Flask app executes is set by the111``FLASK_ENV`` environment variable. When using the ``flask`` command, it112can also be set with the ``--env`` option. If not set it defaults to113``production``. The other recognized environment is ``development``.114Flask and extensions may choose to enable behaviors based on the115environment.116117If the env is set to ``development``, the ``flask`` command will enable118debug mode and ``flask run`` will enable the interactive debugger and119reloader.120121.. code-block:: text122123     $ flask --app hello --env development run124      * Serving Flask app "hello"125      * Environment: development126      * Debug mode: on127      * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)128      * Restarting with inotify reloader129      * Debugger is active!130      * Debugger PIN: 223-456-919131132133Watch Extra Files with the Reloader134~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~135136When using development mode, the reloader will trigger whenever your137Python code or imported modules change. The reloader can watch138additional files with the ``--extra-files`` option. Multiple paths are139separated with ``:``, or ``;`` on Windows.140141.. code-block:: text142143    $ flask run --extra-files file1:dirA/file2:dirB/144     * Running on http://127.0.0.1:8000/145     * Detected change in '/path/to/file1', reloading146147148Ignore files with the Reloader149~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~150151The reloader can also ignore files using :mod:`fnmatch` patterns with152the ``--exclude-patterns`` option. Multiple patterns are separated with153``:``, or ``;`` on Windows.154155156Debug Mode157----------158159Debug mode will be enabled when the execution environment is160``development``, as described above. If you want to control debug mode161separately, use the ``--debug/--no-debug`` option or the ``FLASK_DEBUG``162environment variable.163164165.. _dotenv:166167Environment Variables From dotenv168---------------------------------169170The ``flask`` command supports setting any option for any command with171environment variables. The variables are named like ``FLASK_OPTION`` or172``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or173``FLASK_RUN_PORT``.174175Rather than passing options every time you run a command, or environment176variables every time you open a new terminal, you can use Flask's dotenv177support to set environment variables automatically.178179If `python-dotenv`_ is installed, running the ``flask`` command will set180environment variables defined in the files ``.env`` and ``.flaskenv``.181You can also specify an extra file to load with the ``--env-file``182option. Dotenv files can be used to avoid having to set ``--app`` or183``FLASK_APP`` manually, and to set configuration using environment184variables similar to how some deployment services work.185186Variables set on the command line are used over those set in :file:`.env`,187which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be188used for public variables, such as ``FLASK_APP``, while :file:`.env` should not189be committed to your repository so that it can set private variables.190191Directories are scanned upwards from the directory you call ``flask``192from to locate the files.193194The files are only loaded by the ``flask`` command or calling195:meth:`~Flask.run`. If you would like to load these files when running in196production, you should call :func:`~cli.load_dotenv` manually.197198.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme199200201Setting Command Options202~~~~~~~~~~~~~~~~~~~~~~~203204Click is configured to load default values for command options from205environment variables. The variables use the pattern206``FLASK_COMMAND_OPTION``. For example, to set the port for the run207command, instead of ``flask run --port 8000``:208209.. tabs::210211   .. group-tab:: Bash212213      .. code-block:: text214215         $ export FLASK_RUN_PORT=8000216         $ flask run217          * Running on http://127.0.0.1:8000/218219   .. group-tab:: Fish220221      .. code-block:: text222223         $ set -x FLASK_RUN_PORT 8000224         $ flask run225          * Running on http://127.0.0.1:8000/226227   .. group-tab:: CMD228229      .. code-block:: text230231         > set FLASK_RUN_PORT=8000232         > flask run233          * Running on http://127.0.0.1:8000/234235   .. group-tab:: Powershell236237      .. code-block:: text238239         > $env:FLASK_RUN_PORT = 8000240         > flask run241          * Running on http://127.0.0.1:8000/242243These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to244control default command options.245246247Disable dotenv248~~~~~~~~~~~~~~249250The ``flask`` command will show a message if it detects dotenv files but251python-dotenv is not installed.252253.. code-block:: bash254255    $ flask run256     * Tip: There are .env files present. Do "pip install python-dotenv" to use them.257258You can tell Flask not to load dotenv files even when python-dotenv is259installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.260This can be useful if you want to load them manually, or if you're using261a project runner that loads them already. Keep in mind that the262environment variables must be set before the app loads or it won't263configure as expected.264265.. tabs::266267   .. group-tab:: Bash268269      .. code-block:: text270271         $ export FLASK_SKIP_DOTENV=1272         $ flask run273274   .. group-tab:: Fish275276      .. code-block:: text277278         $ set -x FLASK_SKIP_DOTENV 1279         $ flask run280281   .. group-tab:: CMD282283      .. code-block:: text284285         > set FLASK_SKIP_DOTENV=1286         > flask run287288   .. group-tab:: Powershell289290      .. code-block:: text291292         > $env:FLASK_SKIP_DOTENV = 1293         > flask run294295296Environment Variables From virtualenv297-------------------------------------298299If you do not want to install dotenv support, you can still set environment300variables by adding them to the end of the virtualenv's :file:`activate`301script. Activating the virtualenv will set the variables.302303.. tabs::304305   .. group-tab:: Bash306307      Unix Bash, :file:`venv/bin/activate`::308309          $ export FLASK_APP=hello310311   .. group-tab:: Fish312313      Fish, :file:`venv/bin/activate.fish`::314315          $ set -x FLASK_APP hello316317   .. group-tab:: CMD318319      Windows CMD, :file:`venv\\Scripts\\activate.bat`::320321          > set FLASK_APP=hello322323   .. group-tab:: Powershell324325      Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::326327          > $env:FLASK_APP = "hello"328329It is preferred to use dotenv support over this, since :file:`.flaskenv` can be330committed to the repository so that it works automatically wherever the project331is checked out.332333334Custom Commands335---------------336337The ``flask`` command is implemented using `Click`_. See that project's338documentation for full information about writing commands.339340This example adds the command ``create-user`` that takes the argument341``name``. ::342343    import click344    from flask import Flask345346    app = Flask(__name__)347348    @app.cli.command("create-user")349    @click.argument("name")350    def create_user(name):351        ...352353::354355    $ flask create-user admin356357This example adds the same command, but as ``user create``, a command in a358group. This is useful if you want to organize multiple related commands. ::359360    import click361    from flask import Flask362    from flask.cli import AppGroup363364    app = Flask(__name__)365    user_cli = AppGroup('user')366367    @user_cli.command('create')368    @click.argument('name')369    def create_user(name):370        ...371372    app.cli.add_command(user_cli)373374::375376    $ flask user create demo377378See :ref:`testing-cli` for an overview of how to test your custom379commands.380381382Registering Commands with Blueprints383~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~384385If your application uses blueprints, you can optionally register CLI386commands directly onto them. When your blueprint is registered onto your387application, the associated commands will be available to the ``flask``388command. By default, those commands will be nested in a group matching389the name of the blueprint.390391.. code-block:: python392393    from flask import Blueprint394395    bp = Blueprint('students', __name__)396397    @bp.cli.command('create')398    @click.argument('name')399    def create(name):400        ...401402    app.register_blueprint(bp)403404.. code-block:: text405406    $ flask students create alice407408You can alter the group name by specifying the ``cli_group`` parameter409when creating the :class:`Blueprint` object, or later with410:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.411The following are equivalent:412413.. code-block:: python414415    bp = Blueprint('students', __name__, cli_group='other')416    # or417    app.register_blueprint(bp, cli_group='other')418419.. code-block:: text420421    $ flask other create alice422423Specifying ``cli_group=None`` will remove the nesting and merge the424commands directly to the application's level:425426.. code-block:: python427428    bp = Blueprint('students', __name__, cli_group=None)429    # or430    app.register_blueprint(bp, cli_group=None)431432.. code-block:: text433434    $ flask create alice435436437Application Context438~~~~~~~~~~~~~~~~~~~439440Commands added using the Flask app's :attr:`~Flask.cli` or441:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator442will be executed with an application context pushed, so your custom443commands and parameters have access to the app and its configuration. The444:func:`~cli.with_appcontext` decorator can be used to get the same445behavior, but is not needed in most cases.446447.. code-block:: python448449    import click450    from flask.cli import with_appcontext451452    @click.command()453    @with_appcontext454    def do_work():455        ...456457    app.cli.add_command(do_work)458459460Plugins461-------462463Flask will automatically load commands specified in the ``flask.commands``464`entry point`_. This is useful for extensions that want to add commands when465they are installed. Entry points are specified in :file:`setup.py` ::466467    from setuptools import setup468469    setup(470        name='flask-my-extension',471        ...,472        entry_points={473            'flask.commands': [474                'my-command=flask_my_extension.commands:cli'475            ],476        },477    )478479480.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points481482Inside :file:`flask_my_extension/commands.py` you can then export a Click483object::484485    import click486487    @click.command()488    def cli():489        ...490491Once that package is installed in the same virtualenv as your Flask project,492you can run ``flask my-command`` to invoke the command.493494495.. _custom-scripts:496497Custom Scripts498--------------499500When you are using the app factory pattern, it may be more convenient to define501your own Click script. Instead of using ``--app`` and letting Flask load502your application, you can create your own Click object and export it as a503`console script`_ entry point.504505Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::506507    import click508    from flask import Flask509    from flask.cli import FlaskGroup510511    def create_app():512        app = Flask('wiki')513        # other setup514        return app515516    @click.group(cls=FlaskGroup, create_app=create_app)517    def cli():518        """Management script for the Wiki application."""519520Define the entry point in :file:`setup.py`::521522    from setuptools import setup523524    setup(525        name='flask-my-extension',526        ...,527        entry_points={528            'console_scripts': [529                'wiki=wiki:cli'530            ],531        },532    )533534Install the application in the virtualenv in editable mode and the custom535script is available. Note that you don't need to set ``--app``. ::536537    $ pip install -e .538    $ wiki run539540.. admonition:: Errors in Custom Scripts541542    When using a custom script, if you introduce an error in your543    module-level code, the reloader will fail because it can no longer544    load the entry point.545546    The ``flask`` command, being separate from your code, does not have547    this issue and is recommended in most cases.548549.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts550551552PyCharm Integration553-------------------554555PyCharm Professional provides a special Flask run configuration. For556the Community Edition, we need to configure it to call the ``flask run``557CLI command with the correct environment variables. These instructions558should be similar for any other IDE you might want to use.559560In PyCharm, with your project open, click on *Run* from the menu bar and561go to *Edit Configurations*. You'll be greeted by a screen similar to562this:563564.. image:: _static/pycharm-runconfig.png565    :align: center566    :class: screenshot567    :alt: Screenshot of PyCharms's run configuration settings.568569There's quite a few options to change, but once we've done it for one570command, we can easily copy the entire configuration and make a single571tweak to give us access to other commands, including any custom ones you572may implement yourself.573574Click the + (*Add New Configuration*) button and select *Python*. Give575the configuration a name such as "flask run". For the ``flask run``576command, check "Single instance only" since you can't run the server577more than once at the same time.578579Select *Module name* from the dropdown (**A**) then input ``flask``.580581The *Parameters* field (**B**) is set to the CLI command to execute582(with any arguments). In this example we use ``run``, which will run583the development server.584585You can skip this next step if you're using :ref:`dotenv`. We need to586add an environment variable (**C**) to identify our application. Click587on the browse button and add an entry with ``FLASK_APP`` on the left and588the Python import or file on the right (``hello`` for example). Add an589entry with ``FLASK_ENV`` and set it to ``development``.590591Next we need to set the working directory (**D**) to be the folder where592our application resides.593594If you have installed your project as a package in your virtualenv, you595may untick the *PYTHONPATH* options (**E**). This will more accurately596match how you deploy the app later.597598Click *Apply* to save the configuration, or *OK* to save and close the599window. Select the configuration in the main PyCharm window and click600the play button next to it to run the server.601602Now that we have a configuration which runs ``flask run`` from within603PyCharm, we can copy that configuration and alter the *Script* argument604to run a different CLI command, e.g. ``flask shell``.