Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

608 lines · 17.8 KiB

Last changed by

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

History of this file

Take it

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

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 1–17why, 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.1011.. _Click: https://click.palletsprojects.com/121314Application Discovery15---------------------1617The ``flask`` command is installed by Flask, not your application; it must be

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 18–19why, one step back
18told where to find your application in order to use it. The ``--app``
19option is used to specify how to load the application.

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

line 20why, one step back
20

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 21why, one step back
21While ``--app`` supports a variety of options for specifying your

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 22–24why, one step back
22application, most use cases should be simple. Here are the typical values:
2324(nothing)

Merge pull request #3999 from greyli/improve-cli-docsDavid Lordbefore adoption28262c3

lines 25–27why, one step back
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``).

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

line 28why, one step back
28

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 29why, one step back
29``--app hello``

Merge pull request #3999 from greyli/improve-cli-docsDavid Lordbefore adoption28262c3

lines 30–31why, one step back
30 The given name is imported, automatically detecting an app (``app``
31 or ``application``) or factory (``create_app`` or ``make_app``).

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 32–34why, one step back
32
33----34

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 35why, one step back
35``--app`` has three parts: an optional path that sets the current working

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 36–40why, one step back
36directory, a Python file or dotted import path, and an optional variable
37name of the instance or factory. If the name is a factory, it can optionally38be followed by arguments in parentheses. The following values demonstrate these39parts:40

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 41why, one step back
41``--app src/hello``

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 42–43why, one step back
42 Sets the current working directory to ``src`` then imports ``hello``.
43

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 44why, one step back
44``--app hello.web``

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 45–46why, one step back
45 Imports the path ``hello.web``.
46

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 47why, one step back
47``--app hello:app2``

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 48–49why, one step back
48 Uses the ``app2`` Flask instance in ``hello``.
49

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 50why, one step back
50``--app 'hello:create_app("dev")'``

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 51–53why, one step back
51 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``
52 as the argument.53

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 54why, one step back
54If ``--app`` is not set, the command will try to import "app" or

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 55–82why, one step back
55"wsgi" (as a ".py" file, or package) and try to detect an application
56instance 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.82

Merge branch '2.0.x'David Lordbefore adoptionedac7e3

lines 83–87why, one step back
83If another program is already using port 5000, you'll see
84``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the85server tries to start. See :ref:`address-already-in-use` for how to86handle that.87

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 88–96why, one step back
88
89Open 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 shell

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

lines 97–99why, one step back
97 Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux
98 App: example [production]99 Instance: /home/david/Projects/pallets/flask/instance

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 100–109why, one step back
100 >>>
101102Use :meth:`~Flask.shell_context_processor` to add other automatic imports.103104105Environments106------------107108.. versionadded:: 1.0109

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 110–112why, one step back
110The environment in which the Flask app executes is set by the
111``FLASK_ENV`` environment variable. When using the ``flask`` command, it112can also be set with the ``--env`` option. If not set it defaults to

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 113–120why, one step back
113``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.120

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 121why, one step back
121.. code-block:: text

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

line 122why, one step back
122

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 123–130why, one step back
123 $ flask --app hello --env development run
124 * 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-919

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 131–137why, one step back
131
132133Watch Extra Files with the Reloader134~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~135136When using development mode, the reloader will trigger whenever your137Python code or imported modules change. The reloader can watch

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 138why, one step back
138additional files with the ``--extra-files`` option. Multiple paths are

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 139–140why, one step back
139separated with ``:``, or ``;`` on Windows.
140

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 141why, one step back
141.. code-block:: text

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

line 142why, one step back
142

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 143–145why, one step back
143 $ flask run --extra-files file1:dirA/file2:dirB/
144 * Running on http://127.0.0.1:8000/145 * Detected change in '/path/to/file1', reloading

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 146–147why, one step back
146
147

Merge pull request #4189 from mgu/feat/use-exclude-patterns-reloaderDavid Lordbefore adoption48ee204

lines 148–151why, one step back
148Ignore files with the Reloader
149~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~150151The reloader can also ignore files using :mod:`fnmatch` patterns with

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 152–153why, one step back
152the ``--exclude-patterns`` option. Multiple patterns are separated with
153``:``, or ``;`` on Windows.

Merge pull request #4189 from mgu/feat/use-exclude-patterns-reloaderDavid Lordbefore adoption48ee204

lines 154–155why, one step back
154
155

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 156–158why, one step back
156Debug Mode
157----------158

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 159–162why, one step back
159Debug mode will be enabled when the execution environment is
160``development``, as described above. If you want to control debug mode161separately, use the ``--debug/--no-debug`` option or the ``FLASK_DEBUG``162environment variable.

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 163–169why, one step back
163
164165.. _dotenv:166167Environment Variables From dotenv168---------------------------------169

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 170–173why, one step back
170The ``flask`` command supports setting any option for any command with
171environment variables. The variables are named like ``FLASK_OPTION`` or172``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or173``FLASK_RUN_PORT``.

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

line 174why, one step back
174

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 175–178why, one step back
175Rather than passing options every time you run a command, or environment
176variables every time you open a new terminal, you can use Flask's dotenv177support to set environment variables automatically.178

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

line 179why, one step back
179If `python-dotenv`_ is installed, running the ``flask`` command will set

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 180–184why, one step back
180environment 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.

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 185–191why, one step back
185
186Variables 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``

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoptiona25d234

line 192why, one step back
192from to locate the files.

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 193–218why, one step back
193
194The 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/218

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 219–226why, one step back
219 .. group-tab:: Fish
220221 .. code-block:: text222223 $ set -x FLASK_RUN_PORT 8000224 $ flask run225 * Running on http://127.0.0.1:8000/226

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 227–273why, one step back
227 .. group-tab:: CMD
228229 .. 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 run273

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 274–280why, one step back
274 .. group-tab:: Fish
275276 .. code-block:: text277278 $ set -x FLASK_SKIP_DOTENV 1279 $ flask run280

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 281–309why, one step back
281 .. group-tab:: CMD
282283 .. 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=hello

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 310–315why, one step back
310
311 .. group-tab:: Fish312313 Fish, :file:`venv/bin/activate.fish`::314315 $ set -x FLASK_APP hello

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 316–504why, one step back
316
317 .. 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`441:meth:`~cli.AppGroup.command` decorator will be executed with an application442context pushed, so your command and extensions have access to the app and its443configuration. If you create a command using the Click :func:`~click.command`444decorator instead of the Flask decorator, you can use445:func:`~cli.with_appcontext` to get the same behavior. ::446447 import click448 from flask.cli import with_appcontext449450 @click.command()451 @with_appcontext452 def do_work():453 ...454455 app.cli.add_command(do_work)456457If you're sure a command doesn't need the context, you can disable it::458459 @app.cli.command(with_appcontext=False)460 def do_work():461 ...462463464Plugins465-------466467Flask will automatically load commands specified in the ``flask.commands``468`entry point`_. This is useful for extensions that want to add commands when469they are installed. Entry points are specified in :file:`setup.py` ::470471 from setuptools import setup472473 setup(474 name='flask-my-extension',475 ...,476 entry_points={477 'flask.commands': [478 'my-command=flask_my_extension.commands:cli'479 ],480 },481 )482483484.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points485486Inside :file:`flask_my_extension/commands.py` you can then export a Click487object::488489 import click490491 @click.command()492 def cli():493 ...494495Once that package is installed in the same virtualenv as your Flask project,496you can run ``flask my-command`` to invoke the command.497498499.. _custom-scripts:500501Custom Scripts502--------------503504When you are using the app factory pattern, it may be more convenient to define

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 505why, one step back
505your own Click script. Instead of using ``--app`` and letting Flask load

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 506–538why, one step back
506your application, you can create your own Click object and export it as a
507`console script`_ entry point.508509Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::510511 import click512 from flask import Flask513 from flask.cli import FlaskGroup514515 def create_app():516 app = Flask('wiki')517 # other setup518 return app519520 @click.group(cls=FlaskGroup, create_app=create_app)521 def cli():522 """Management script for the Wiki application."""523524Define the entry point in :file:`setup.py`::525526 from setuptools import setup527528 setup(529 name='flask-my-extension',530 ...,531 entry_points={532 'console_scripts': [533 'wiki=wiki:cli'534 ],535 },536 )537538Install the application in the virtualenv in editable mode and the custom

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 539why, one step back
539script is available. Note that you don't need to set ``--app``. ::

Bump pytest from 6.1.1 to 6.1.2 (#3818)dependabot-preview[bot]before adoption3b57c19

lines 540–608why, one step back
540
541 $ pip install -e .542 $ wiki run543544.. admonition:: Errors in Custom Scripts545546 When using a custom script, if you introduce an error in your547 module-level code, the reloader will fail because it can no longer548 load the entry point.549550 The ``flask`` command, being separate from your code, does not have551 this issue and is recommended in most cases.552553.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts554555556PyCharm Integration557-------------------558559PyCharm Professional provides a special Flask run configuration. For560the Community Edition, we need to configure it to call the ``flask run``561CLI command with the correct environment variables. These instructions562should be similar for any other IDE you might want to use.563564In PyCharm, with your project open, click on *Run* from the menu bar and565go to *Edit Configurations*. You'll be greeted by a screen similar to566this:567568.. image:: _static/pycharm-runconfig.png569 :align: center570 :class: screenshot571 :alt: Screenshot of PyCharms's run configuration settings.572573There's quite a few options to change, but once we've done it for one574command, we can easily copy the entire configuration and make a single575tweak to give us access to other commands, including any custom ones you576may implement yourself.577578Click the + (*Add New Configuration*) button and select *Python*. Give579the configuration a name such as "flask run". For the ``flask run``580command, check "Single instance only" since you can't run the server581more than once at the same time.582583Select *Module name* from the dropdown (**A**) then input ``flask``.584585The *Parameters* field (**B**) is set to the CLI command to execute586(with any arguments). In this example we use ``run``, which will run587the development server.588589You can skip this next step if you're using :ref:`dotenv`. We need to590add an environment variable (**C**) to identify our application. Click591on the browse button and add an entry with ``FLASK_APP`` on the left and592the Python import or file on the right (``hello`` for example). Add an593entry with ``FLASK_ENV`` and set it to ``development``.594595Next we need to set the working directory (**D**) to be the folder where596our application resides.597598If you have installed your project as a package in your virtualenv, you599may untick the *PYTHONPATH* options (**E**). This will more accurately600match how you deploy the app later.601602Click *Apply* to save the configuration, or *OK* to save and close the603window. Select the configuration in the main PyCharm window and click604the play button next to it to run the server.605606Now that we have a configuration which runs ``flask run`` from within607PyCharm, we can copy that configuration and alter the *Script* argument608to run a different CLI command, e.g. ``flask shell``.