Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

556 lines · 16.3 KiB

Last changed by

Not known.

History of this file

Take it

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

Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660

lines 1–556why, 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 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. ::7374 $ flask --app hello 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.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.878889Debug Mode90~~~~~~~~~~9192In 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.9596.. code-block:: console9798 $ flask --app hello run --debug99 * 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-919105106The ``--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 --debug113114115Watch and Ignore Files with the Reloader116~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~117118When 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.121122.. 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', reloading127128The reloader can also ignore files using :mod:`fnmatch` patterns with the129``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on130Windows.131132133Open a Shell134------------135136To 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. ::139140 $ 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 >>>145146Use :meth:`~Flask.shell_context_processor` to add other automatic imports.147148149.. _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:: Bash290291 Unix Bash, :file:`.venv/bin/activate`::292293 $ export FLASK_APP=hello294295 .. group-tab:: Fish296297 Fish, :file:`.venv/bin/activate.fish`::298299 $ set -x FLASK_APP hello300301 .. group-tab:: CMD302303 Windows CMD, :file:`.venv\\Scripts\\activate.bat`::304305 > set FLASK_APP=hello306307 .. group-tab:: Powershell308309 Windows Powershell, :file:`.venv\\Scripts\\activate.ps1`::310311 > $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 when449they are installed. Entry points are specified in :file:`pyproject.toml`:450451.. code-block:: toml452453 [project.entry-points."flask.commands"]454 my-command = "my_extension.commands:cli"455456.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points457458Inside :file:`my_extension/commands.py` you can then export a Click459object::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."""495496Define the entry point in :file:`pyproject.toml`:497498.. code-block:: toml499500 [project.scripts]501 wiki = "wiki:cli"502503Install 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-------------------523524PyCharm 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.528529In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit530Configurations*. You'll see a screen similar to this:531532.. image:: _static/pycharm-run-config.png533 :align: center534 :class: screenshot535 :alt: Screenshot of PyCharm run configuration.536537Once you create a configuration for the ``flask run``, you can copy and change it to538call any other command.539540Click the *+ (Add New Configuration)* button and select *Python*. Give the configuration541a name such as "flask run".542543Click the *Script path* dropdown and change it to *Module name*, then input ``flask``.544545The *Parameters* field is set to the CLI command to execute along with any arguments.546This example uses ``--app hello run --debug``, which will run the development server in547debug mode. ``--app hello`` should be the import or file with your Flask app.548549If 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.551552Click *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.554555Now that you have a configuration for ``flask run``, you can copy that configuration and556change the *Parameters* argument to run a different CLI command.