cli.rst
This file
Path
docs/cli.rst
556 lines · 16.3 KiB
Last changed by
Merge branch '2.2.x'David Lordbefore adoptioned5b240
History of this fileTake it
The walk stopped after 200 commits: lines older than 979e0ad point at it.
fix pr linkDavid Lordbefore adoption979e0ad
lines 1–73why, one step back1.. 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. ::73Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 74why, one step back74 $ flask --app hello runfix pr linkDavid Lordbefore adoption979e0ad
lines 75–88why, one step back75 * 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.8788Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 89–90why, one step back89Debug Mode90~~~~~~~~~~fix pr linkDavid Lordbefore adoption979e0ad
line 91why, one step back91Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 92–94why, one step back92In debug mode, the ``flask run`` command will enable the interactive debugger and the93reloader by default, and make errors easier to see and debug. To enable debug mode, use94the ``--debug`` option.fix pr linkDavid Lordbefore adoption979e0ad
line 95why, one step back95Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 96why, one step back96.. code-block:: consolefix pr linkDavid Lordbefore adoption979e0ad
line 97why, one step back97new run debug docsDavid Lordbefore adoption74e5263
line 98why, one step back98 $ flask --app hello run --debugfix pr linkDavid Lordbefore adoption979e0ad
lines 99–105why, one step back99 * Serving Flask app "hello"100 * Debug mode: on101 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)102 * Restarting with inotify reloader103 * Debugger is active!104 * Debugger PIN: 223-456-919105Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 106–113why, one step back106The ``--debug`` option can also be passed to the top level ``flask`` command to enable107debug mode for any command. The following two ``run`` calls are equivalent.108109.. code-block:: console110111 $ flask --app hello --debug run112 $ flask --app hello run --debug113fix pr linkDavid Lordbefore adoption979e0ad
line 114why, one step back114Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 115–116why, one step back115Watch and Ignore Files with the Reloader116~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~fix pr linkDavid Lordbefore adoption979e0ad
line 117why, one step back117Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 118–120why, one step back118When using debug mode, the reloader will trigger whenever your Python code or imported119modules change. The reloader can watch additional files with the ``--extra-files``120option. Multiple paths are separated with ``:``, or ``;`` on Windows.fix pr linkDavid Lordbefore adoption979e0ad
lines 121–127why, one step back121122.. code-block:: text123124 $ flask run --extra-files file1:dirA/file2:dirB/125 * Running on http://127.0.0.1:8000/126 * Detected change in '/path/to/file1', reloading127Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 128–130why, one step back128The reloader can also ignore files using :mod:`fnmatch` patterns with the129``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on130Windows.fix pr linkDavid Lordbefore adoption979e0ad
lines 131–132why, one step back131132Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 133–134why, one step back133Open a Shell134------------fix pr linkDavid Lordbefore adoption979e0ad
line 135why, one step back135Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 136–138why, one step back136To explore the data in your application, you can start an interactive Python137shell with the :func:`shell <cli.shell_command>` command. An application138context will be active, and the app instance will be imported. ::fix pr linkDavid Lordbefore adoption979e0ad
line 139why, one step back139Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 140–144why, one step back140 $ flask shell141 Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux142 App: example [production]143 Instance: /home/david/Projects/pallets/flask/instance144 >>>fix pr linkDavid Lordbefore adoption979e0ad
line 145why, one step back145Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 146why, one step back146Use :meth:`~Flask.shell_context_processor` to add other automatic imports.fix pr linkDavid Lordbefore adoption979e0ad
lines 147–290why, one step back147148149.. _dotenv:150151Environment Variables From dotenv152---------------------------------153154The ``flask`` command supports setting any option for any command with155environment variables. The variables are named like ``FLASK_OPTION`` or156``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or157``FLASK_RUN_PORT``.158159Rather than passing options every time you run a command, or environment160variables every time you open a new terminal, you can use Flask's dotenv161support to set environment variables automatically.162163If `python-dotenv`_ is installed, running the ``flask`` command will set164environment variables defined in the files ``.env`` and ``.flaskenv``.165You can also specify an extra file to load with the ``--env-file``166option. Dotenv files can be used to avoid having to set ``--app`` or167``FLASK_APP`` manually, and to set configuration using environment168variables similar to how some deployment services work.169170Variables set on the command line are used over those set in :file:`.env`,171which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be172used for public variables, such as ``FLASK_APP``, while :file:`.env` should not173be committed to your repository so that it can set private variables.174175Directories are scanned upwards from the directory you call ``flask``176from to locate the files.177178The files are only loaded by the ``flask`` command or calling179:meth:`~Flask.run`. If you would like to load these files when running in180production, you should call :func:`~cli.load_dotenv` manually.181182.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme183184185Setting Command Options186~~~~~~~~~~~~~~~~~~~~~~~187188Click is configured to load default values for command options from189environment variables. The variables use the pattern190``FLASK_COMMAND_OPTION``. For example, to set the port for the run191command, instead of ``flask run --port 8000``:192193.. tabs::194195 .. group-tab:: Bash196197 .. code-block:: text198199 $ export FLASK_RUN_PORT=8000200 $ flask run201 * Running on http://127.0.0.1:8000/202203 .. group-tab:: Fish204205 .. code-block:: text206207 $ set -x FLASK_RUN_PORT 8000208 $ flask run209 * Running on http://127.0.0.1:8000/210211 .. group-tab:: CMD212213 .. code-block:: text214215 > set FLASK_RUN_PORT=8000216 > flask run217 * Running on http://127.0.0.1:8000/218219 .. group-tab:: Powershell220221 .. code-block:: text222223 > $env:FLASK_RUN_PORT = 8000224 > flask run225 * Running on http://127.0.0.1:8000/226227These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to228control default command options.229230231Disable dotenv232~~~~~~~~~~~~~~233234The ``flask`` command will show a message if it detects dotenv files but235python-dotenv is not installed.236237.. code-block:: bash238239 $ flask run240 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.241242You can tell Flask not to load dotenv files even when python-dotenv is243installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.244This can be useful if you want to load them manually, or if you're using245a project runner that loads them already. Keep in mind that the246environment variables must be set before the app loads or it won't247configure as expected.248249.. tabs::250251 .. group-tab:: Bash252253 .. code-block:: text254255 $ export FLASK_SKIP_DOTENV=1256 $ flask run257258 .. group-tab:: Fish259260 .. code-block:: text261262 $ set -x FLASK_SKIP_DOTENV 1263 $ flask run264265 .. group-tab:: CMD266267 .. code-block:: text268269 > set FLASK_SKIP_DOTENV=1270 > flask run271272 .. group-tab:: Powershell273274 .. code-block:: text275276 > $env:FLASK_SKIP_DOTENV = 1277 > flask run278279280Environment Variables From virtualenv281-------------------------------------282283If you do not want to install dotenv support, you can still set environment284variables by adding them to the end of the virtualenv's :file:`activate`285script. Activating the virtualenv will set the variables.286287.. tabs::288289 .. group-tab:: Bash290Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 291why, one step back291 Unix Bash, :file:`.venv/bin/activate`::fix pr linkDavid Lordbefore adoption979e0ad
lines 292–296why, one step back292293 $ export FLASK_APP=hello294295 .. group-tab:: Fish296Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 297why, one step back297 Fish, :file:`.venv/bin/activate.fish`::fix pr linkDavid Lordbefore adoption979e0ad
lines 298–302why, one step back298299 $ set -x FLASK_APP hello300301 .. group-tab:: CMD302Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 303why, one step back303 Windows CMD, :file:`.venv\\Scripts\\activate.bat`::fix pr linkDavid Lordbefore adoption979e0ad
lines 304–308why, one step back304305 > set FLASK_APP=hello306307 .. group-tab:: Powershell308Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 309why, one step back309 Windows Powershell, :file:`.venv\\Scripts\\activate.ps1`::fix pr linkDavid Lordbefore adoption979e0ad
lines 310–448why, one step back310311 > $env:FLASK_APP = "hello"312313It is preferred to use dotenv support over this, since :file:`.flaskenv` can be314committed to the repository so that it works automatically wherever the project315is checked out.316317318Custom Commands319---------------320321The ``flask`` command is implemented using `Click`_. See that project's322documentation for full information about writing commands.323324This example adds the command ``create-user`` that takes the argument325``name``. ::326327 import click328 from flask import Flask329330 app = Flask(__name__)331332 @app.cli.command("create-user")333 @click.argument("name")334 def create_user(name):335 ...336337::338339 $ flask create-user admin340341This example adds the same command, but as ``user create``, a command in a342group. This is useful if you want to organize multiple related commands. ::343344 import click345 from flask import Flask346 from flask.cli import AppGroup347348 app = Flask(__name__)349 user_cli = AppGroup('user')350351 @user_cli.command('create')352 @click.argument('name')353 def create_user(name):354 ...355356 app.cli.add_command(user_cli)357358::359360 $ flask user create demo361362See :ref:`testing-cli` for an overview of how to test your custom363commands.364365366Registering Commands with Blueprints367~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~368369If your application uses blueprints, you can optionally register CLI370commands directly onto them. When your blueprint is registered onto your371application, the associated commands will be available to the ``flask``372command. By default, those commands will be nested in a group matching373the name of the blueprint.374375.. code-block:: python376377 from flask import Blueprint378379 bp = Blueprint('students', __name__)380381 @bp.cli.command('create')382 @click.argument('name')383 def create(name):384 ...385386 app.register_blueprint(bp)387388.. code-block:: text389390 $ flask students create alice391392You can alter the group name by specifying the ``cli_group`` parameter393when creating the :class:`Blueprint` object, or later with394:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.395The following are equivalent:396397.. code-block:: python398399 bp = Blueprint('students', __name__, cli_group='other')400 # or401 app.register_blueprint(bp, cli_group='other')402403.. code-block:: text404405 $ flask other create alice406407Specifying ``cli_group=None`` will remove the nesting and merge the408commands directly to the application's level:409410.. code-block:: python411412 bp = Blueprint('students', __name__, cli_group=None)413 # or414 app.register_blueprint(bp, cli_group=None)415416.. code-block:: text417418 $ flask create alice419420421Application Context422~~~~~~~~~~~~~~~~~~~423424Commands added using the Flask app's :attr:`~Flask.cli` or425:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator426will be executed with an application context pushed, so your custom427commands and parameters have access to the app and its configuration. The428:func:`~cli.with_appcontext` decorator can be used to get the same429behavior, but is not needed in most cases.430431.. code-block:: python432433 import click434 from flask.cli import with_appcontext435436 @click.command()437 @with_appcontext438 def do_work():439 ...440441 app.cli.add_command(do_work)442443444Plugins445-------446447Flask will automatically load commands specified in the ``flask.commands``448`entry point`_. This is useful for extensions that want to add commands whenMerge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 449why, one step back449they are installed. Entry points are specified in :file:`pyproject.toml`:fix pr linkDavid Lordbefore adoption979e0ad
line 450why, one step back450Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 451why, one step back451.. code-block:: tomlfix pr linkDavid Lordbefore adoption979e0ad
line 452why, one step back452Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
lines 453–454why, one step back453 [project.entry-points."flask.commands"]454 my-command = "my_extension.commands:cli"fix pr linkDavid Lordbefore adoption979e0ad
lines 455–457why, one step back455456.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points457Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 458why, one step back458Inside :file:`my_extension/commands.py` you can then export a Clickfix pr linkDavid Lordbefore adoption979e0ad
lines 459–495why, one step back459object::460461 import click462463 @click.command()464 def cli():465 ...466467Once that package is installed in the same virtualenv as your Flask project,468you can run ``flask my-command`` to invoke the command.469470471.. _custom-scripts:472473Custom Scripts474--------------475476When you are using the app factory pattern, it may be more convenient to define477your own Click script. Instead of using ``--app`` and letting Flask load478your application, you can create your own Click object and export it as a479`console script`_ entry point.480481Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::482483 import click484 from flask import Flask485 from flask.cli import FlaskGroup486487 def create_app():488 app = Flask('wiki')489 # other setup490 return app491492 @click.group(cls=FlaskGroup, create_app=create_app)493 def cli():494 """Management script for the Wiki application."""495Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 496why, one step back496Define the entry point in :file:`pyproject.toml`:fix pr linkDavid Lordbefore adoption979e0ad
line 497why, one step back497Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 498why, one step back498.. code-block:: tomlfix pr linkDavid Lordbefore adoption979e0ad
line 499why, one step back499Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
lines 500–501why, one step back500 [project.scripts]501 wiki = "wiki:cli"fix pr linkDavid Lordbefore adoption979e0ad
lines 502–523why, one step back502503Install the application in the virtualenv in editable mode and the custom504script is available. Note that you don't need to set ``--app``. ::505506 $ pip install -e .507 $ wiki run508509.. admonition:: Errors in Custom Scripts510511 When using a custom script, if you introduce an error in your512 module-level code, the reloader will fail because it can no longer513 load the entry point.514515 The ``flask`` command, being separate from your code, does not have516 this issue and is recommended in most cases.517518.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts519520521PyCharm Integration522-------------------523Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 524–527why, one step back524PyCharm Professional provides a special Flask run configuration to run the development525server. For the Community Edition, and for other commands besides ``run``, you need to526create a custom run configuration. These instructions should be similar for any other527IDE you use.fix pr linkDavid Lordbefore adoption979e0ad
line 528why, one step back528Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 529–530why, one step back529In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit530Configurations*. You'll see a screen similar to this:fix pr linkDavid Lordbefore adoption979e0ad
line 531why, one step back531Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 532why, one step back532.. image:: _static/pycharm-run-config.pngfix pr linkDavid Lordbefore adoption979e0ad
lines 533–534why, one step back533 :align: center534 :class: screenshotMerge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 535why, one step back535 :alt: Screenshot of PyCharm run configuration.fix pr linkDavid Lordbefore adoption979e0ad
line 536why, one step back536Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 537–538why, one step back537Once you create a configuration for the ``flask run``, you can copy and change it to538call any other command.fix pr linkDavid Lordbefore adoption979e0ad
line 539why, one step back539Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 540–541why, one step back540Click the *+ (Add New Configuration)* button and select *Python*. Give the configuration541a name such as "flask run".fix pr linkDavid Lordbefore adoption979e0ad
line 542why, one step back542Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 543why, one step back543Click the *Script path* dropdown and change it to *Module name*, then input ``flask``.fix pr linkDavid Lordbefore adoption979e0ad
line 544why, one step back544Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 545why, one step back545The *Parameters* field is set to the CLI command to execute along with any arguments.new run debug docsDavid Lordbefore adoption74e5263
line 546why, one step back546This example uses ``--app hello run --debug``, which will run the development server inMerge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 547why, one step back547debug mode. ``--app hello`` should be the import or file with your Flask app.fix pr linkDavid Lordbefore adoption979e0ad
line 548why, one step back548Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 549–550why, one step back549If you installed your project as a package in your virtualenv, you may uncheck the550*PYTHONPATH* options. This will more accurately match how you deploy later.fix pr linkDavid Lordbefore adoption979e0ad
line 551why, one step back551Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 552–553why, one step back552Click *OK* to save and close the configuration. Select the configuration in the main553PyCharm window and click the play button next to it to run the server.fix pr linkDavid Lordbefore adoption979e0ad
line 554why, one step back554Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
lines 555–556why, one step back555Now that you have a configuration for ``flask run``, you can copy that configuration and556change the *Parameters* argument to run a different CLI command.