Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

537 lines · 16.2 KiB

Last changed by

Merge pull request #3564 from pallets/cli-ast-parseDavid Lordbefore adoption2062d98

History of this file

Take it

The walk stopped after 200 commits: lines older than d0214c9 point at it.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 1–10why, one step back
1.. currentmodule:: flask
23Command 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.10

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 11why, one step back
11.. _Click: https://click.palletsprojects.com/

use name of licenseDavid Lordbefore adoptiond0214c9

lines 12–68why, one step back
12
1314Application 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.2021Unix Bash (Linux, Mac, etc.)::2223 $ export FLASK_APP=hello24 $ flask run2526Windows CMD::2728 > set FLASK_APP=hello29 > flask run3031Windows PowerShell::3233 > $env:FLASK_APP = "hello"34 > flask run3536While ``FLASK_APP`` supports a variety of options for specifying your37application, most use cases should be simple. Here are the typical values:3839(nothing)40 The file :file:`wsgi.py` is imported, automatically detecting an app41 (``app``). This provides an easy way to create an app from a factory with42 extra arguments.4344``FLASK_APP=hello``45 The name is imported, automatically detecting an app (``app``) or factory46 (``create_app``).4748----4950``FLASK_APP`` has three parts: an optional path that sets the current working51directory, a Python file or dotted import path, and an optional variable52name of the instance or factory. If the name is a factory, it can optionally53be followed by arguments in parentheses. The following values demonstrate these54parts:5556``FLASK_APP=src/hello``57 Sets the current working directory to ``src`` then imports ``hello``.5859``FLASK_APP=hello.web``60 Imports the path ``hello.web``.6162``FLASK_APP=hello:app2``63 Uses the ``app2`` Flask instance in ``hello``.6465``FLASK_APP="hello:create_app('dev')"``66 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``67 as the argument.68

Merge branch '1.0.x'David Lordbefore adoption2236ba9

lines 69–71why, one step back
69If ``FLASK_APP`` is not set, the command will try to import "app" or
70"wsgi" (as a ".py" file, or package) and try to detect an application71instance or factory.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 72–77why, one step back
72
73Within the given import, the command looks for an application instance named74``app`` or ``application``, then any application instance. If no instance is75found, the command looks for a factory function named ``create_app`` or76``make_app`` that returns an instance.77

Merge pull request #3563 from pallets/deprecate-script-info-argDavid Lordbefore adoption0d04b40

line 78why, one step back
78If parentheses follow the factory name, their contents are parsed as

Merge pull request #3564 from pallets/cli-ast-parseDavid Lordbefore adoption2062d98

lines 79–80why, one step back
79Python literals and passed as arguments and keyword arguments to the
80function. This means that strings must still be in quotes.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 81–95why, one step back
81
8283Run the Development Server84--------------------------8586The :func:`run <cli.run_command>` command will start the development server. It87replaces the :meth:`Flask.run` method in most cases. ::8889 $ flask run90 * Serving Flask app "hello"91 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)9293.. warning:: Do not use this command to run your application in production.94 Only use the development server during development. The development server95 is provided for convenience, but is not designed to be particularly secure,

remove unused ref directivesDavid Lordbefore adoption171aabc

line 96why, one step back
96 stable, or efficient. See :doc:`/deploying/index` for how to run in production.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 97–142why, one step back
97
9899Open a Shell100------------101102To explore the data in your application, you can start an interactive Python103shell with the :func:`shell <cli.shell_command>` command. An application104context will be active, and the app instance will be imported. ::105106 $ flask shell107 Python 3.6.2 (default, Jul 20 2017, 03:52:27)108 [GCC 7.1.1 20170630] on linux109 App: example110 Instance: /home/user/Projects/hello/instance111 >>>112113Use :meth:`~Flask.shell_context_processor` to add other automatic imports.114115116Environments117------------118119.. versionadded:: 1.0120121The environment in which the Flask app runs is set by the122:envvar:`FLASK_ENV` environment variable. If not set it defaults to123``production``. The other recognized environment is ``development``.124Flask and extensions may choose to enable behaviors based on the125environment.126127If the env is set to ``development``, the ``flask`` command will enable128debug mode and ``flask run`` will enable the interactive debugger and129reloader.130131::132133 $ FLASK_ENV=development flask run134 * Serving Flask app "hello"135 * Environment: development136 * Debug mode: on137 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)138 * Restarting with inotify reloader139 * Debugger is active!140 * Debugger PIN: 223-456-919141142

Merge pull request #2898 from rochacbruno/2897-Add-Extra-Files-to-CLIDavid Lordbefore adoption2616d97

lines 143–161why, one step back
143Watch Extra Files with the Reloader
144~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~145146When using development mode, the reloader will trigger whenever your147Python code or imported modules change. The reloader can watch148additional files with the ``--extra-files`` option, or the149``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are150separated with ``:``, or ``;`` on Windows.151152.. code-block:: none153154 $ flask run --extra-files file1:dirA/file2:dirB/155 # or156 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/157 $ flask run158 * Running on http://127.0.0.1:8000/159 * Detected change in '/path/to/file1', reloading160161

use name of licenseDavid Lordbefore adoptiond0214c9

lines 162–208why, one step back
162Debug Mode
163----------164165Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,166as described above. If you want to control debug mode separately, use167:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.168169170.. _dotenv:171172Environment Variables From dotenv173---------------------------------174175Rather than setting ``FLASK_APP`` each time you open a new terminal, you can176use Flask's dotenv support to set environment variables automatically.177178If `python-dotenv`_ is installed, running the ``flask`` command will set179environment variables defined in the files :file:`.env` and :file:`.flaskenv`.180This can be used to avoid having to set ``FLASK_APP`` manually every time you181open a new terminal, and to set configuration using environment variables182similar to how some deployment services work.183184Variables set on the command line are used over those set in :file:`.env`,185which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be186used for public variables, such as ``FLASK_APP``, while :file:`.env` should not187be committed to your repository so that it can set private variables.188189Directories are scanned upwards from the directory you call ``flask``190from to locate the files. The current working directory will be set to the191location of the file, with the assumption that that is the top level project192directory.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``:208

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

line 209why, one step back
209.. code-block:: bash

use name of licenseDavid Lordbefore adoptiond0214c9

line 210why, one step back
210

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

lines 211–212why, one step back
211 $ export FLASK_RUN_PORT=8000
212 $ flask run

use name of licenseDavid Lordbefore adoptiond0214c9

lines 213–218why, one step back
213 * Running on http://127.0.0.1:8000/
214215These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to216control default command options.217218

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

lines 219–224why, one step back
219Disable dotenv
220~~~~~~~~~~~~~~221222The ``flask`` command will show a message if it detects dotenv files but223python-dotenv is not installed.224

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

line 225why, one step back
225.. code-block:: bash

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

line 226why, one step back
226

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 227why, one step back
227 $ flask run

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

lines 228–236why, one step back
228 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.
229230You can tell Flask not to load dotenv files even when python-dotenv is231installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.232This can be useful if you want to load them manually, or if you're using233a project runner that loads them already. Keep in mind that the234environment variables must be set before the app loads or it won't235configure as expected.236

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

line 237why, one step back
237.. code-block:: bash

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

line 238why, one step back
238

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

lines 239–240why, one step back
239 $ export FLASK_SKIP_DOTENV=1
240 $ flask run

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

lines 241–242why, one step back
241
242

use name of licenseDavid Lordbefore adoptiond0214c9

lines 243–251why, one step back
243Environment Variables From virtualenv
244-------------------------------------245246If you do not want to install dotenv support, you can still set environment247variables by adding them to the end of the virtualenv's :file:`activate`248script. Activating the virtualenv will set the variables.249250Unix Bash, :file:`venv/bin/activate`::251

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 252why, one step back
252 $ export FLASK_APP=hello

use name of licenseDavid Lordbefore adoptiond0214c9

lines 253–255why, one step back
253
254Windows CMD, :file:`venv\\Scripts\\activate.bat`::255

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 256why, one step back
256 > set FLASK_APP=hello

use name of licenseDavid Lordbefore adoptiond0214c9

lines 257–268why, one step back
257
258It is preferred to use dotenv support over this, since :file:`.flaskenv` can be259committed to the repository so that it works automatically wherever the project260is checked out.261262263Custom Commands264---------------265266The ``flask`` command is implemented using `Click`_. See that project's267documentation for full information about writing commands.268

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 269why, one step back
269This example adds the command ``create-user`` that takes the argument

use name of licenseDavid Lordbefore adoptiond0214c9

lines 270–276why, one step back
270``name``. ::
271272 import click273 from flask import Flask274275 app = Flask(__name__)276

Merge branch '1.0.x'David Lordbefore adoption1351d0a

lines 277–278why, one step back
277 @app.cli.command("create-user")
278 @click.argument("name")

use name of licenseDavid Lordbefore adoptiond0214c9

lines 279–283why, one step back
279 def create_user(name):
280 ...281282::283

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 284why, one step back
284 $ flask create-user admin

use name of licenseDavid Lordbefore adoptiond0214c9

lines 285–304why, one step back
285
286This example adds the same command, but as ``user create``, a command in a287group. This is useful if you want to organize multiple related commands. ::288289 import click290 from flask import Flask291 from flask.cli import AppGroup292293 app = Flask(__name__)294 user_cli = AppGroup('user')295296 @user_cli.command('create')297 @click.argument('name')298 def create_user(name):299 ...300301 app.cli.add_command(user_cli)302303::304

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 305why, one step back
305 $ flask user create demo

use name of licenseDavid Lordbefore adoptiond0214c9

lines 306–308why, one step back
306
307See :ref:`testing-cli` for an overview of how to test your custom308commands.

Merge pull request #2784 from doobeh/masterDavid Lordbefore adoptionb837606

lines 309–363why, one step back
309
310311Registering Commands with Blueprints312~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~313314If your application uses blueprints, you can optionally register CLI315commands directly onto them. When your blueprint is registered onto your316application, the associated commands will be available to the ``flask``317command. By default, those commands will be nested in a group matching318the name of the blueprint.319320.. code-block:: python321322 from flask import Blueprint323324 bp = Blueprint('students', __name__)325326 @bp.cli.command('create')327 @click.argument('name')328 def create(name):329 ...330331 app.register_blueprint(bp)332333.. code-block:: text334335 $ flask students create alice336337You can alter the group name by specifying the ``cli_group`` parameter338when creating the :class:`Blueprint` object, or later with339:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.340The following are equivalent:341342.. code-block:: python343344 bp = Blueprint('students', __name__, cli_group='other')345 # or346 app.register_blueprint(bp, cli_group='other')347348.. code-block:: text349350 $ flask other create alice351352Specifying ``cli_group=None`` will remove the nesting and merge the353commands directly to the application's level:354355.. code-block:: python356357 bp = Blueprint('students', __name__, cli_group=None)358 # or359 app.register_blueprint(bp, cli_group=None)360361.. code-block:: text362363 $ flask create alice

use name of licenseDavid Lordbefore adoptiond0214c9

lines 364–378why, one step back
364
365366Application Context367~~~~~~~~~~~~~~~~~~~368369Commands added using the Flask app's :attr:`~Flask.cli`370:meth:`~cli.AppGroup.command` decorator will be executed with an application371context pushed, so your command and extensions have access to the app and its372configuration. If you create a command using the Click :func:`~click.command`373decorator instead of the Flask decorator, you can use374:func:`~cli.with_appcontext` to get the same behavior. ::375376 import click377 from flask.cli import with_appcontext378

Merge pull request #2915 from loomchild/masterDavid Lordbefore adoptionc92001d

line 379why, one step back
379 @click.command()

use name of licenseDavid Lordbefore adoptiond0214c9

lines 380–412why, one step back
380 @with_appcontext
381 def do_work():382 ...383384 app.cli.add_command(do_work)385386If you're sure a command doesn't need the context, you can disable it::387388 @app.cli.command(with_appcontext=False)389 def do_work():390 ...391392393Plugins394-------395396Flask will automatically load commands specified in the ``flask.commands``397`entry point`_. This is useful for extensions that want to add commands when398they are installed. Entry points are specified in :file:`setup.py` ::399400 from setuptools import setup401402 setup(403 name='flask-my-extension',404 ...,405 entry_points={406 'flask.commands': [407 'my-command=flask_my_extension.commands:cli'408 ],409 },410 )411412

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 413why, one step back
413.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points

use name of licenseDavid Lordbefore adoptiond0214c9

lines 414–481why, one step back
414
415Inside :file:`flask_my_extension/commands.py` you can then export a Click416object::417418 import click419420 @click.command()421 def cli():422 ...423424Once that package is installed in the same virtualenv as your Flask project,425you can run ``flask my-command`` to invoke the command.426427428.. _custom-scripts:429430Custom Scripts431--------------432433When you are using the app factory pattern, it may be more convenient to define434your own Click script. Instead of using ``FLASK_APP`` and letting Flask load435your application, you can create your own Click object and export it as a436`console script`_ entry point.437438Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::439440 import click441 from flask import Flask442 from flask.cli import FlaskGroup443444 def create_app():445 app = Flask('wiki')446 # other setup447 return app448449 @click.group(cls=FlaskGroup, create_app=create_app)450 def cli():451 """Management script for the Wiki application."""452453Define the entry point in :file:`setup.py`::454455 from setuptools import setup456457 setup(458 name='flask-my-extension',459 ...,460 entry_points={461 'console_scripts': [462 'wiki=wiki:cli'463 ],464 },465 )466467Install the application in the virtualenv in editable mode and the custom468script is available. Note that you don't need to set ``FLASK_APP``. ::469470 $ pip install -e .471 $ wiki run472473.. admonition:: Errors in Custom Scripts474475 When using a custom script, if you introduce an error in your476 module-level code, the reloader will fail because it can no longer477 load the entry point.478479 The ``flask`` command, being separate from your code, does not have480 this issue and is recommended in most cases.481

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 482why, one step back
482.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts

use name of licenseDavid Lordbefore adoptiond0214c9

lines 483–487why, one step back
483
484485PyCharm Integration486-------------------487

Merge branch '1.1.x'David Lordbefore adoption96b4dca

lines 488–491why, one step back
488PyCharm Professional provides a special Flask run configuration. For
489the Community Edition, we need to configure it to call the ``flask run``490CLI command with the correct environment variables. These instructions491should be similar for any other IDE you might want to use.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 492–499why, one step back
492
493In PyCharm, with your project open, click on *Run* from the menu bar and494go to *Edit Configurations*. You'll be greeted by a screen similar to495this:496497.. image:: _static/pycharm-runconfig.png498 :align: center499 :class: screenshot

Merge branch '1.1.x'David Lordbefore adoption96b4dca

line 500why, one step back
500 :alt: Screenshot of PyCharms's run configuration settings.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 501–507why, one step back
501
502There's quite a few options to change, but once we've done it for one503command, we can easily copy the entire configuration and make a single504tweak to give us access to other commands, including any custom ones you505may implement yourself.506507Click the + (*Add New Configuration*) button and select *Python*. Give

Merge branch '1.1.x'David Lordbefore adoption96b4dca

lines 508–510why, one step back
508the configuration a name such as "flask run". For the ``flask run``
509command, check "Single instance only" since you can't run the server510more than once at the same time.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 511–520why, one step back
511
512Select *Module name* from the dropdown (**A**) then input ``flask``.513514The *Parameters* field (**B**) is set to the CLI command to execute515(with any arguments). In this example we use ``run``, which will run516the development server.517518You can skip this next step if you're using :ref:`dotenv`. We need to519add an environment variable (**C**) to identify our application. Click520on the browse button and add an entry with ``FLASK_APP`` on the left and

Merge branch '1.1.x'David Lordbefore adoption96b4dca

lines 521–522why, one step back
521the Python import or file on the right (``hello`` for example). Add an
522entry with ``FLASK_ENV`` and set it to ``development``.

use name of licenseDavid Lordbefore adoptiond0214c9

lines 523–537why, one step back
523
524Next we need to set the working directory (**D**) to be the folder where525our application resides.526527If you have installed your project as a package in your virtualenv, you528may untick the *PYTHONPATH* options (**E**). This will more accurately529match how you deploy the app later.530531Click *Apply* to save the configuration, or *OK* to save and close the532window. Select the configuration in the main PyCharm window and click533the play button next to it to run the server.534535Now that we have a configuration which runs ``flask run`` from within536PyCharm, we can copy that configuration and alter the *Script* argument537to run a different CLI command, e.g. ``flask shell``.