Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

712 lines · 20.2 KiB

Last changed by

Merge pull request #4412 from otherJL0/mainDavid Lordbefore adoption981a94d

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:: Fish3132      .. code-block:: text3334         $ set -x FLASK_APP hello35         $ flask run3637   .. group-tab:: CMD3839      .. code-block:: text4041         > set FLASK_APP=hello42         > flask run4344   .. group-tab:: Powershell4546      .. code-block:: text4748         > $env:FLASK_APP = "hello"49         > flask run5051While ``FLASK_APP`` supports a variety of options for specifying your52application, most use cases should be simple. Here are the typical values:5354(nothing)55    The name "app" or "wsgi" is imported (as a ".py" file, or package),56    automatically detecting an app (``app`` or ``application``) or57    factory (``create_app`` or ``make_app``).5859``FLASK_APP=hello``60    The given name is imported, automatically detecting an app (``app``61    or ``application``) or factory (``create_app`` or ``make_app``).6263----6465``FLASK_APP`` has three parts: an optional path that sets the current working66directory, a Python file or dotted import path, and an optional variable67name of the instance or factory. If the name is a factory, it can optionally68be followed by arguments in parentheses. The following values demonstrate these69parts:7071``FLASK_APP=src/hello``72    Sets the current working directory to ``src`` then imports ``hello``.7374``FLASK_APP=hello.web``75    Imports the path ``hello.web``.7677``FLASK_APP=hello:app2``78    Uses the ``app2`` Flask instance in ``hello``.7980``FLASK_APP="hello:create_app('dev')"``81    The ``create_app`` factory in ``hello`` is called with the string ``'dev'``82    as the argument.8384If ``FLASK_APP`` is not set, the command will try to import "app" or85"wsgi" (as a ".py" file, or package) and try to detect an application86instance or factory.8788Within the given import, the command looks for an application instance named89``app`` or ``application``, then any application instance. If no instance is90found, the command looks for a factory function named ``create_app`` or91``make_app`` that returns an instance.9293If parentheses follow the factory name, their contents are parsed as94Python literals and passed as arguments and keyword arguments to the95function. This means that strings must still be in quotes.969798Run the Development Server99--------------------------100101The :func:`run <cli.run_command>` command will start the development server. It102replaces the :meth:`Flask.run` method in most cases. ::103104    $ flask run105     * Serving Flask app "hello"106     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)107108.. warning:: Do not use this command to run your application in production.109    Only use the development server during development. The development server110    is provided for convenience, but is not designed to be particularly secure,111    stable, or efficient. See :doc:`/deploying/index` for how to run in production.112113If another program is already using port 5000, you'll see114``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the115server tries to start. See :ref:`address-already-in-use` for how to116handle that.117118119Open a Shell120------------121122To explore the data in your application, you can start an interactive Python123shell with the :func:`shell <cli.shell_command>` command. An application124context will be active, and the app instance will be imported. ::125126    $ flask shell127    Python 3.6.2 (default, Jul 20 2017, 03:52:27)128    [GCC 7.1.1 20170630] on linux129    App: example130    Instance: /home/user/Projects/hello/instance131    >>>132133Use :meth:`~Flask.shell_context_processor` to add other automatic imports.134135136Environments137------------138139.. versionadded:: 1.0140141The environment in which the Flask app runs is set by the142:envvar:`FLASK_ENV` environment variable. If not set it defaults to143``production``. The other recognized environment is ``development``.144Flask and extensions may choose to enable behaviors based on the145environment.146147If the env is set to ``development``, the ``flask`` command will enable148debug mode and ``flask run`` will enable the interactive debugger and149reloader.150151.. tabs::152153   .. group-tab:: Bash154155      .. code-block:: text156157         $ export FLASK_ENV=development158         $ flask run159          * Serving Flask app "hello"160          * Environment: development161          * Debug mode: on162          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)163          * Restarting with inotify reloader164          * Debugger is active!165          * Debugger PIN: 223-456-919166167   .. group-tab:: Fish168169      .. code-block:: text170171         $ set -x FLASK_ENV development172         $ flask run173          * Serving Flask app "hello"174          * Environment: development175          * Debug mode: on176          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)177          * Restarting with inotify reloader178          * Debugger is active!179          * Debugger PIN: 223-456-919180181   .. group-tab:: CMD182183      .. code-block:: text184185         > set FLASK_ENV=development186         > flask run187          * Serving Flask app "hello"188          * Environment: development189          * Debug mode: on190          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)191          * Restarting with inotify reloader192          * Debugger is active!193          * Debugger PIN: 223-456-919194195   .. group-tab:: Powershell196197      .. code-block:: text198199         > $env:FLASK_ENV = "development"200         > flask run201          * Serving Flask app "hello"202          * Environment: development203          * Debug mode: on204          * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)205          * Restarting with inotify reloader206          * Debugger is active!207          * Debugger PIN: 223-456-919208209210Watch Extra Files with the Reloader211~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~212213When using development mode, the reloader will trigger whenever your214Python code or imported modules change. The reloader can watch215additional files with the ``--extra-files`` option, or the216``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are217separated with ``:``, or ``;`` on Windows.218219.. tabs::220221   .. group-tab:: Bash222223      .. code-block:: text224225          $ flask run --extra-files file1:dirA/file2:dirB/226          # or227          $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/228          $ flask run229           * Running on http://127.0.0.1:8000/230           * Detected change in '/path/to/file1', reloading231232   .. group-tab:: Fish233234      .. code-block:: text235236          $ flask run --extra-files file1:dirA/file2:dirB/237          # or238          $ set -x FLASK_RUN_EXTRA_FILES file1 dirA/file2 dirB/239          $ flask run240           * Running on http://127.0.0.1:8000/241           * Detected change in '/path/to/file1', reloading242243   .. group-tab:: CMD244245      .. code-block:: text246247          > flask run --extra-files file1:dirA/file2:dirB/248          # or249          > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/250          > flask run251           * Running on http://127.0.0.1:8000/252           * Detected change in '/path/to/file1', reloading253254   .. group-tab:: Powershell255256      .. code-block:: text257258          > flask run --extra-files file1:dirA/file2:dirB/259          # or260          > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"261          > flask run262           * Running on http://127.0.0.1:8000/263           * Detected change in '/path/to/file1', reloading264265266Debug Mode267----------268269Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,270as described above. If you want to control debug mode separately, use271:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.272273274.. _dotenv:275276Environment Variables From dotenv277---------------------------------278279Rather than setting ``FLASK_APP`` each time you open a new terminal, you can280use Flask's dotenv support to set environment variables automatically.281282If `python-dotenv`_ is installed, running the ``flask`` command will set283environment variables defined in the files :file:`.env` and :file:`.flaskenv`.284This can be used to avoid having to set ``FLASK_APP`` manually every time you285open a new terminal, and to set configuration using environment variables286similar to how some deployment services work.287288Variables set on the command line are used over those set in :file:`.env`,289which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be290used for public variables, such as ``FLASK_APP``, while :file:`.env` should not291be committed to your repository so that it can set private variables.292293Directories are scanned upwards from the directory you call ``flask``294from to locate the files. The current working directory will be set to the295location of the file, with the assumption that that is the top level project296directory.297298The files are only loaded by the ``flask`` command or calling299:meth:`~Flask.run`. If you would like to load these files when running in300production, you should call :func:`~cli.load_dotenv` manually.301302.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme303304305Setting Command Options306~~~~~~~~~~~~~~~~~~~~~~~307308Click is configured to load default values for command options from309environment variables. The variables use the pattern310``FLASK_COMMAND_OPTION``. For example, to set the port for the run311command, instead of ``flask run --port 8000``:312313.. tabs::314315   .. group-tab:: Bash316317      .. code-block:: text318319         $ export FLASK_RUN_PORT=8000320         $ flask run321          * Running on http://127.0.0.1:8000/322323   .. group-tab:: Fish324325      .. code-block:: text326327         $ set -x FLASK_RUN_PORT 8000328         $ flask run329          * Running on http://127.0.0.1:8000/330331   .. group-tab:: CMD332333      .. code-block:: text334335         > set FLASK_RUN_PORT=8000336         > flask run337          * Running on http://127.0.0.1:8000/338339   .. group-tab:: Powershell340341      .. code-block:: text342343         > $env:FLASK_RUN_PORT = 8000344         > flask run345          * Running on http://127.0.0.1:8000/346347These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to348control default command options.349350351Disable dotenv352~~~~~~~~~~~~~~353354The ``flask`` command will show a message if it detects dotenv files but355python-dotenv is not installed.356357.. code-block:: bash358359    $ flask run360     * Tip: There are .env files present. Do "pip install python-dotenv" to use them.361362You can tell Flask not to load dotenv files even when python-dotenv is363installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.364This can be useful if you want to load them manually, or if you're using365a project runner that loads them already. Keep in mind that the366environment variables must be set before the app loads or it won't367configure as expected.368369.. tabs::370371   .. group-tab:: Bash372373      .. code-block:: text374375         $ export FLASK_SKIP_DOTENV=1376         $ flask run377378   .. group-tab:: Fish379380      .. code-block:: text381382         $ set -x FLASK_SKIP_DOTENV 1383         $ flask run384385   .. group-tab:: CMD386387      .. code-block:: text388389         > set FLASK_SKIP_DOTENV=1390         > flask run391392   .. group-tab:: Powershell393394      .. code-block:: text395396         > $env:FLASK_SKIP_DOTENV = 1397         > flask run398399400Environment Variables From virtualenv401-------------------------------------402403If you do not want to install dotenv support, you can still set environment404variables by adding them to the end of the virtualenv's :file:`activate`405script. Activating the virtualenv will set the variables.406407.. tabs::408409   .. group-tab:: Bash410411      Unix Bash, :file:`venv/bin/activate`::412413          $ export FLASK_APP=hello414415   .. group-tab:: Fish416417      Fish, :file:`venv/bin/activate.fish`::418419          $ set -x FLASK_APP hello420421   .. group-tab:: CMD422423      Windows CMD, :file:`venv\\Scripts\\activate.bat`::424425          > set FLASK_APP=hello426427   .. group-tab:: Powershell428429      Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::430431          > $env:FLASK_APP = "hello"432433It is preferred to use dotenv support over this, since :file:`.flaskenv` can be434committed to the repository so that it works automatically wherever the project435is checked out.436437438Custom Commands439---------------440441The ``flask`` command is implemented using `Click`_. See that project's442documentation for full information about writing commands.443444This example adds the command ``create-user`` that takes the argument445``name``. ::446447    import click448    from flask import Flask449450    app = Flask(__name__)451452    @app.cli.command("create-user")453    @click.argument("name")454    def create_user(name):455        ...456457::458459    $ flask create-user admin460461This example adds the same command, but as ``user create``, a command in a462group. This is useful if you want to organize multiple related commands. ::463464    import click465    from flask import Flask466    from flask.cli import AppGroup467468    app = Flask(__name__)469    user_cli = AppGroup('user')470471    @user_cli.command('create')472    @click.argument('name')473    def create_user(name):474        ...475476    app.cli.add_command(user_cli)477478::479480    $ flask user create demo481482See :ref:`testing-cli` for an overview of how to test your custom483commands.484485486Registering Commands with Blueprints487~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~488489If your application uses blueprints, you can optionally register CLI490commands directly onto them. When your blueprint is registered onto your491application, the associated commands will be available to the ``flask``492command. By default, those commands will be nested in a group matching493the name of the blueprint.494495.. code-block:: python496497    from flask import Blueprint498499    bp = Blueprint('students', __name__)500501    @bp.cli.command('create')502    @click.argument('name')503    def create(name):504        ...505506    app.register_blueprint(bp)507508.. code-block:: text509510    $ flask students create alice511512You can alter the group name by specifying the ``cli_group`` parameter513when creating the :class:`Blueprint` object, or later with514:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.515The following are equivalent:516517.. code-block:: python518519    bp = Blueprint('students', __name__, cli_group='other')520    # or521    app.register_blueprint(bp, cli_group='other')522523.. code-block:: text524525    $ flask other create alice526527Specifying ``cli_group=None`` will remove the nesting and merge the528commands directly to the application's level:529530.. code-block:: python531532    bp = Blueprint('students', __name__, cli_group=None)533    # or534    app.register_blueprint(bp, cli_group=None)535536.. code-block:: text537538    $ flask create alice539540541Application Context542~~~~~~~~~~~~~~~~~~~543544Commands added using the Flask app's :attr:`~Flask.cli`545:meth:`~cli.AppGroup.command` decorator will be executed with an application546context pushed, so your command and extensions have access to the app and its547configuration. If you create a command using the Click :func:`~click.command`548decorator instead of the Flask decorator, you can use549:func:`~cli.with_appcontext` to get the same behavior. ::550551    import click552    from flask.cli import with_appcontext553554    @click.command()555    @with_appcontext556    def do_work():557        ...558559    app.cli.add_command(do_work)560561If you're sure a command doesn't need the context, you can disable it::562563    @app.cli.command(with_appcontext=False)564    def do_work():565        ...566567568Plugins569-------570571Flask will automatically load commands specified in the ``flask.commands``572`entry point`_. This is useful for extensions that want to add commands when573they are installed. Entry points are specified in :file:`setup.py` ::574575    from setuptools import setup576577    setup(578        name='flask-my-extension',579        ...,580        entry_points={581            'flask.commands': [582                'my-command=flask_my_extension.commands:cli'583            ],584        },585    )586587588.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points589590Inside :file:`flask_my_extension/commands.py` you can then export a Click591object::592593    import click594595    @click.command()596    def cli():597        ...598599Once that package is installed in the same virtualenv as your Flask project,600you can run ``flask my-command`` to invoke the command.601602603.. _custom-scripts:604605Custom Scripts606--------------607608When you are using the app factory pattern, it may be more convenient to define609your own Click script. Instead of using ``FLASK_APP`` and letting Flask load610your application, you can create your own Click object and export it as a611`console script`_ entry point.612613Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::614615    import click616    from flask import Flask617    from flask.cli import FlaskGroup618619    def create_app():620        app = Flask('wiki')621        # other setup622        return app623624    @click.group(cls=FlaskGroup, create_app=create_app)625    def cli():626        """Management script for the Wiki application."""627628Define the entry point in :file:`setup.py`::629630    from setuptools import setup631632    setup(633        name='flask-my-extension',634        ...,635        entry_points={636            'console_scripts': [637                'wiki=wiki:cli'638            ],639        },640    )641642Install the application in the virtualenv in editable mode and the custom643script is available. Note that you don't need to set ``FLASK_APP``. ::644645    $ pip install -e .646    $ wiki run647648.. admonition:: Errors in Custom Scripts649650    When using a custom script, if you introduce an error in your651    module-level code, the reloader will fail because it can no longer652    load the entry point.653654    The ``flask`` command, being separate from your code, does not have655    this issue and is recommended in most cases.656657.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts658659660PyCharm Integration661-------------------662663PyCharm Professional provides a special Flask run configuration. For664the Community Edition, we need to configure it to call the ``flask run``665CLI command with the correct environment variables. These instructions666should be similar for any other IDE you might want to use.667668In PyCharm, with your project open, click on *Run* from the menu bar and669go to *Edit Configurations*. You'll be greeted by a screen similar to670this:671672.. image:: _static/pycharm-runconfig.png673    :align: center674    :class: screenshot675    :alt: Screenshot of PyCharms's run configuration settings.676677There's quite a few options to change, but once we've done it for one678command, we can easily copy the entire configuration and make a single679tweak to give us access to other commands, including any custom ones you680may implement yourself.681682Click the + (*Add New Configuration*) button and select *Python*. Give683the configuration a name such as "flask run". For the ``flask run``684command, check "Single instance only" since you can't run the server685more than once at the same time.686687Select *Module name* from the dropdown (**A**) then input ``flask``.688689The *Parameters* field (**B**) is set to the CLI command to execute690(with any arguments). In this example we use ``run``, which will run691the development server.692693You can skip this next step if you're using :ref:`dotenv`. We need to694add an environment variable (**C**) to identify our application. Click695on the browse button and add an entry with ``FLASK_APP`` on the left and696the Python import or file on the right (``hello`` for example). Add an697entry with ``FLASK_ENV`` and set it to ``development``.698699Next we need to set the working directory (**D**) to be the folder where700our application resides.701702If you have installed your project as a package in your virtualenv, you703may untick the *PYTHONPATH* options (**E**). This will more accurately704match how you deploy the app later.705706Click *Apply* to save the configuration, or *OK* to save and close the707window. Select the configuration in the main PyCharm window and click708the play button next to it to run the server.709710Now that we have a configuration which runs ``flask run`` from within711PyCharm, we can copy that configuration and alter the *Script* argument712to run a different CLI command, e.g. ``flask shell``.