Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

653 lines · 18.8 KiB

Last changed by

Merge pull request #4335 from pallets/drop-python-3.6David Lordbefore adoptionea93a52

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.105106107Open a Shell108------------109110To explore the data in your application, you can start an interactive Python111shell with the :func:`shell <cli.shell_command>` command. An application112context will be active, and the app instance will be imported. ::113114    $ flask shell115    Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux116    App: example [production]117    Instance: /home/david/Projects/pallets/flask/instance118    >>>119120Use :meth:`~Flask.shell_context_processor` to add other automatic imports.121122123Environments124------------125126.. versionadded:: 1.0127128The environment in which the Flask app runs is set by the129:envvar:`FLASK_ENV` environment variable. If not set it defaults to130``production``. The other recognized environment is ``development``.131Flask and extensions may choose to enable behaviors based on the132environment.133134If the env is set to ``development``, the ``flask`` command will enable135debug mode and ``flask run`` will enable the interactive debugger and136reloader.137138.. tabs::139140   .. group-tab:: Bash141142      .. code-block:: text143144         $ export FLASK_ENV=development145         $ flask run146          * Serving Flask app "hello"147          * Environment: development148          * Debug mode: on149          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)150          * Restarting with inotify reloader151          * Debugger is active!152          * Debugger PIN: 223-456-919153154   .. group-tab:: CMD155156      .. code-block:: text157158         > set FLASK_ENV=development159         > flask run160          * Serving Flask app "hello"161          * Environment: development162          * Debug mode: on163          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)164          * Restarting with inotify reloader165          * Debugger is active!166          * Debugger PIN: 223-456-919167168   .. group-tab:: Powershell169170      .. code-block:: text171172         > $env:FLASK_ENV = "development"173         > flask run174          * Serving Flask app "hello"175          * Environment: development176          * Debug mode: on177          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)178          * Restarting with inotify reloader179          * Debugger is active!180          * Debugger PIN: 223-456-919181182183Watch Extra Files with the Reloader184~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~185186When using development mode, the reloader will trigger whenever your187Python code or imported modules change. The reloader can watch188additional files with the ``--extra-files`` option, or the189``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are190separated with ``:``, or ``;`` on Windows.191192.. tabs::193194   .. group-tab:: Bash195196      .. code-block:: text197198          $ flask run --extra-files file1:dirA/file2:dirB/199          # or200          $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/201          $ flask run202           * Running on http://127.0.0.1:8000/203           * Detected change in '/path/to/file1', reloading204205   .. group-tab:: CMD206207      .. code-block:: text208209          > flask run --extra-files file1:dirA/file2:dirB/210          # or211          > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/212          > flask run213           * Running on http://127.0.0.1:8000/214           * Detected change in '/path/to/file1', reloading215216   .. group-tab:: Powershell217218      .. code-block:: text219220          > flask run --extra-files file1:dirA/file2:dirB/221          # or222          > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"223          > flask run224           * Running on http://127.0.0.1:8000/225           * Detected change in '/path/to/file1', reloading226227228Debug Mode229----------230231Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,232as described above. If you want to control debug mode separately, use233:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.234235236.. _dotenv:237238Environment Variables From dotenv239---------------------------------240241Rather than setting ``FLASK_APP`` each time you open a new terminal, you can242use Flask's dotenv support to set environment variables automatically.243244If `python-dotenv`_ is installed, running the ``flask`` command will set245environment variables defined in the files :file:`.env` and :file:`.flaskenv`.246This can be used to avoid having to set ``FLASK_APP`` manually every time you247open a new terminal, and to set configuration using environment variables248similar to how some deployment services work.249250Variables set on the command line are used over those set in :file:`.env`,251which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be252used for public variables, such as ``FLASK_APP``, while :file:`.env` should not253be committed to your repository so that it can set private variables.254255Directories are scanned upwards from the directory you call ``flask``256from to locate the files. The current working directory will be set to the257location of the file, with the assumption that that is the top level project258directory.259260The files are only loaded by the ``flask`` command or calling261:meth:`~Flask.run`. If you would like to load these files when running in262production, you should call :func:`~cli.load_dotenv` manually.263264.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme265266267Setting Command Options268~~~~~~~~~~~~~~~~~~~~~~~269270Click is configured to load default values for command options from271environment variables. The variables use the pattern272``FLASK_COMMAND_OPTION``. For example, to set the port for the run273command, instead of ``flask run --port 8000``:274275.. tabs::276277   .. group-tab:: Bash278279      .. code-block:: text280281         $ export FLASK_RUN_PORT=8000282         $ flask run283          * Running on http://127.0.0.1:8000/284285   .. group-tab:: CMD286287      .. code-block:: text288289         > set FLASK_RUN_PORT=8000290         > flask run291          * Running on http://127.0.0.1:8000/292293   .. group-tab:: Powershell294295      .. code-block:: text296297         > $env:FLASK_RUN_PORT = 8000298         > flask run299          * Running on http://127.0.0.1:8000/300301These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to302control default command options.303304305Disable dotenv306~~~~~~~~~~~~~~307308The ``flask`` command will show a message if it detects dotenv files but309python-dotenv is not installed.310311.. code-block:: bash312313    $ flask run314     * Tip: There are .env files present. Do "pip install python-dotenv" to use them.315316You can tell Flask not to load dotenv files even when python-dotenv is317installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.318This can be useful if you want to load them manually, or if you're using319a project runner that loads them already. Keep in mind that the320environment variables must be set before the app loads or it won't321configure as expected.322323.. tabs::324325   .. group-tab:: Bash326327      .. code-block:: text328329         $ export FLASK_SKIP_DOTENV=1330         $ flask run331332   .. group-tab:: CMD333334      .. code-block:: text335336         > set FLASK_SKIP_DOTENV=1337         > flask run338339   .. group-tab:: Powershell340341      .. code-block:: text342343         > $env:FLASK_SKIP_DOTENV = 1344         > flask run345346347Environment Variables From virtualenv348-------------------------------------349350If you do not want to install dotenv support, you can still set environment351variables by adding them to the end of the virtualenv's :file:`activate`352script. Activating the virtualenv will set the variables.353354.. tabs::355356   .. group-tab:: Bash357358      Unix Bash, :file:`venv/bin/activate`::359360          $ export FLASK_APP=hello361362   .. group-tab:: CMD363364      Windows CMD, :file:`venv\\Scripts\\activate.bat`::365366          > set FLASK_APP=hello367368   .. group-tab:: Powershell369370      Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::371372          > $env:FLASK_APP = "hello"373374It is preferred to use dotenv support over this, since :file:`.flaskenv` can be375committed to the repository so that it works automatically wherever the project376is checked out.377378379Custom Commands380---------------381382The ``flask`` command is implemented using `Click`_. See that project's383documentation for full information about writing commands.384385This example adds the command ``create-user`` that takes the argument386``name``. ::387388    import click389    from flask import Flask390391    app = Flask(__name__)392393    @app.cli.command("create-user")394    @click.argument("name")395    def create_user(name):396        ...397398::399400    $ flask create-user admin401402This example adds the same command, but as ``user create``, a command in a403group. This is useful if you want to organize multiple related commands. ::404405    import click406    from flask import Flask407    from flask.cli import AppGroup408409    app = Flask(__name__)410    user_cli = AppGroup('user')411412    @user_cli.command('create')413    @click.argument('name')414    def create_user(name):415        ...416417    app.cli.add_command(user_cli)418419::420421    $ flask user create demo422423See :ref:`testing-cli` for an overview of how to test your custom424commands.425426427Registering Commands with Blueprints428~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~429430If your application uses blueprints, you can optionally register CLI431commands directly onto them. When your blueprint is registered onto your432application, the associated commands will be available to the ``flask``433command. By default, those commands will be nested in a group matching434the name of the blueprint.435436.. code-block:: python437438    from flask import Blueprint439440    bp = Blueprint('students', __name__)441442    @bp.cli.command('create')443    @click.argument('name')444    def create(name):445        ...446447    app.register_blueprint(bp)448449.. code-block:: text450451    $ flask students create alice452453You can alter the group name by specifying the ``cli_group`` parameter454when creating the :class:`Blueprint` object, or later with455:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.456The following are equivalent:457458.. code-block:: python459460    bp = Blueprint('students', __name__, cli_group='other')461    # or462    app.register_blueprint(bp, cli_group='other')463464.. code-block:: text465466    $ flask other create alice467468Specifying ``cli_group=None`` will remove the nesting and merge the469commands directly to the application's level:470471.. code-block:: python472473    bp = Blueprint('students', __name__, cli_group=None)474    # or475    app.register_blueprint(bp, cli_group=None)476477.. code-block:: text478479    $ flask create alice480481482Application Context483~~~~~~~~~~~~~~~~~~~484485Commands added using the Flask app's :attr:`~Flask.cli`486:meth:`~cli.AppGroup.command` decorator will be executed with an application487context pushed, so your command and extensions have access to the app and its488configuration. If you create a command using the Click :func:`~click.command`489decorator instead of the Flask decorator, you can use490:func:`~cli.with_appcontext` to get the same behavior. ::491492    import click493    from flask.cli import with_appcontext494495    @click.command()496    @with_appcontext497    def do_work():498        ...499500    app.cli.add_command(do_work)501502If you're sure a command doesn't need the context, you can disable it::503504    @app.cli.command(with_appcontext=False)505    def do_work():506        ...507508509Plugins510-------511512Flask will automatically load commands specified in the ``flask.commands``513`entry point`_. This is useful for extensions that want to add commands when514they are installed. Entry points are specified in :file:`setup.py` ::515516    from setuptools import setup517518    setup(519        name='flask-my-extension',520        ...,521        entry_points={522            'flask.commands': [523                'my-command=flask_my_extension.commands:cli'524            ],525        },526    )527528529.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points530531Inside :file:`flask_my_extension/commands.py` you can then export a Click532object::533534    import click535536    @click.command()537    def cli():538        ...539540Once that package is installed in the same virtualenv as your Flask project,541you can run ``flask my-command`` to invoke the command.542543544.. _custom-scripts:545546Custom Scripts547--------------548549When you are using the app factory pattern, it may be more convenient to define550your own Click script. Instead of using ``FLASK_APP`` and letting Flask load551your application, you can create your own Click object and export it as a552`console script`_ entry point.553554Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::555556    import click557    from flask import Flask558    from flask.cli import FlaskGroup559560    def create_app():561        app = Flask('wiki')562        # other setup563        return app564565    @click.group(cls=FlaskGroup, create_app=create_app)566    def cli():567        """Management script for the Wiki application."""568569Define the entry point in :file:`setup.py`::570571    from setuptools import setup572573    setup(574        name='flask-my-extension',575        ...,576        entry_points={577            'console_scripts': [578                'wiki=wiki:cli'579            ],580        },581    )582583Install the application in the virtualenv in editable mode and the custom584script is available. Note that you don't need to set ``FLASK_APP``. ::585586    $ pip install -e .587    $ wiki run588589.. admonition:: Errors in Custom Scripts590591    When using a custom script, if you introduce an error in your592    module-level code, the reloader will fail because it can no longer593    load the entry point.594595    The ``flask`` command, being separate from your code, does not have596    this issue and is recommended in most cases.597598.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts599600601PyCharm Integration602-------------------603604PyCharm Professional provides a special Flask run configuration. For605the Community Edition, we need to configure it to call the ``flask run``606CLI command with the correct environment variables. These instructions607should be similar for any other IDE you might want to use.608609In PyCharm, with your project open, click on *Run* from the menu bar and610go to *Edit Configurations*. You'll be greeted by a screen similar to611this:612613.. image:: _static/pycharm-runconfig.png614    :align: center615    :class: screenshot616    :alt: Screenshot of PyCharms's run configuration settings.617618There's quite a few options to change, but once we've done it for one619command, we can easily copy the entire configuration and make a single620tweak to give us access to other commands, including any custom ones you621may implement yourself.622623Click the + (*Add New Configuration*) button and select *Python*. Give624the configuration a name such as "flask run". For the ``flask run``625command, check "Single instance only" since you can't run the server626more than once at the same time.627628Select *Module name* from the dropdown (**A**) then input ``flask``.629630The *Parameters* field (**B**) is set to the CLI command to execute631(with any arguments). In this example we use ``run``, which will run632the development server.633634You can skip this next step if you're using :ref:`dotenv`. We need to635add an environment variable (**C**) to identify our application. Click636on the browse button and add an entry with ``FLASK_APP`` on the left and637the Python import or file on the right (``hello`` for example). Add an638entry with ``FLASK_ENV`` and set it to ``development``.639640Next we need to set the working directory (**D**) to be the folder where641our application resides.642643If you have installed your project as a package in your virtualenv, you644may untick the *PYTHONPATH* options (**E**). This will more accurately645match how you deploy the app later.646647Click *Apply* to save the configuration, or *OK* to save and close the648window. Select the configuration in the main PyCharm window and click649the play button next to it to run the server.650651Now that we have a configuration which runs ``flask run`` from within652PyCharm, we can copy that configuration and alter the *Script* argument653to run a different CLI command, e.g. ``flask shell``.