cli.rst
This file
Path
docs/cli.rst
718 lines · 20.4 KiB
Last changed by
Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoptiona25d234
History of this fileTake 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.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux128 App: example [production]129 Instance: /home/david/Projects/pallets/flask/instance130 >>>131132Use :meth:`~Flask.shell_context_processor` to add other automatic imports.133134135Environments136------------137138.. versionadded:: 1.0139140The environment in which the Flask app runs is set by the141:envvar:`FLASK_ENV` environment variable. If not set it defaults to142``production``. The other recognized environment is ``development``.143Flask and extensions may choose to enable behaviors based on the144environment.145146If the env is set to ``development``, the ``flask`` command will enable147debug mode and ``flask run`` will enable the interactive debugger and148reloader.149150.. tabs::151152 .. group-tab:: Bash153154 .. code-block:: text155156 $ export FLASK_ENV=development157 $ flask run158 * Serving Flask app "hello"159 * Environment: development160 * Debug mode: on161 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)162 * Restarting with inotify reloader163 * Debugger is active!164 * Debugger PIN: 223-456-919165166 .. group-tab:: Fish167168 .. code-block:: text169170 $ set -x FLASK_ENV development171 $ flask run172 * Serving Flask app "hello"173 * Environment: development174 * Debug mode: on175 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)176 * Restarting with inotify reloader177 * Debugger is active!178 * Debugger PIN: 223-456-919179180 .. group-tab:: CMD181182 .. code-block:: text183184 > set FLASK_ENV=development185 > flask run186 * Serving Flask app "hello"187 * Environment: development188 * Debug mode: on189 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)190 * Restarting with inotify reloader191 * Debugger is active!192 * Debugger PIN: 223-456-919193194 .. group-tab:: Powershell195196 .. code-block:: text197198 > $env:FLASK_ENV = "development"199 > flask run200 * Serving Flask app "hello"201 * Environment: development202 * Debug mode: on203 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)204 * Restarting with inotify reloader205 * Debugger is active!206 * Debugger PIN: 223-456-919207208209Watch Extra Files with the Reloader210~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~211212When using development mode, the reloader will trigger whenever your213Python code or imported modules change. The reloader can watch214additional files with the ``--extra-files`` option, or the215``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are216separated with ``:``, or ``;`` on Windows.217218.. tabs::219220 .. group-tab:: Bash221222 .. code-block:: text223224 $ flask run --extra-files file1:dirA/file2:dirB/225 # or226 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/227 $ flask run228 * Running on http://127.0.0.1:8000/229 * Detected change in '/path/to/file1', reloading230231 .. group-tab:: Fish232233 .. code-block:: text234235 $ flask run --extra-files file1:dirA/file2:dirB/236 # or237 $ set -x FLASK_RUN_EXTRA_FILES file1 dirA/file2 dirB/238 $ flask run239 * Running on http://127.0.0.1:8000/240 * Detected change in '/path/to/file1', reloading241242 .. group-tab:: CMD243244 .. code-block:: text245246 > flask run --extra-files file1:dirA/file2:dirB/247 # or248 > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/249 > flask run250 * Running on http://127.0.0.1:8000/251 * Detected change in '/path/to/file1', reloading252253 .. group-tab:: Powershell254255 .. code-block:: text256257 > flask run --extra-files file1:dirA/file2:dirB/258 # or259 > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"260 > flask run261 * Running on http://127.0.0.1:8000/262 * Detected change in '/path/to/file1', reloading263264265Ignore files with the Reloader266~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~267268The reloader can also ignore files using :mod:`fnmatch` patterns with269the ``--exclude-patterns`` option, or the ``FLASK_RUN_EXCLUDE_PATTERNS``270environment variable. Multiple patterns are separated with ``:``, or271``;`` on Windows.272273274Debug Mode275----------276277Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,278as described above. If you want to control debug mode separately, use279:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.280281282.. _dotenv:283284Environment Variables From dotenv285---------------------------------286287Rather than setting ``FLASK_APP`` each time you open a new terminal, you can288use Flask's dotenv support to set environment variables automatically.289290If `python-dotenv`_ is installed, running the ``flask`` command will set291environment variables defined in the files :file:`.env` and :file:`.flaskenv`.292This can be used to avoid having to set ``FLASK_APP`` manually every time you293open a new terminal, and to set configuration using environment variables294similar to how some deployment services work.295296Variables set on the command line are used over those set in :file:`.env`,297which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be298used for public variables, such as ``FLASK_APP``, while :file:`.env` should not299be committed to your repository so that it can set private variables.300301Directories are scanned upwards from the directory you call ``flask``302from to locate the files.303304The files are only loaded by the ``flask`` command or calling305:meth:`~Flask.run`. If you would like to load these files when running in306production, you should call :func:`~cli.load_dotenv` manually.307308.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme309310311Setting Command Options312~~~~~~~~~~~~~~~~~~~~~~~313314Click is configured to load default values for command options from315environment variables. The variables use the pattern316``FLASK_COMMAND_OPTION``. For example, to set the port for the run317command, instead of ``flask run --port 8000``:318319.. tabs::320321 .. group-tab:: Bash322323 .. code-block:: text324325 $ export FLASK_RUN_PORT=8000326 $ flask run327 * Running on http://127.0.0.1:8000/328329 .. group-tab:: Fish330331 .. code-block:: text332333 $ set -x FLASK_RUN_PORT 8000334 $ flask run335 * Running on http://127.0.0.1:8000/336337 .. group-tab:: CMD338339 .. code-block:: text340341 > set FLASK_RUN_PORT=8000342 > flask run343 * Running on http://127.0.0.1:8000/344345 .. group-tab:: Powershell346347 .. code-block:: text348349 > $env:FLASK_RUN_PORT = 8000350 > flask run351 * Running on http://127.0.0.1:8000/352353These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to354control default command options.355356357Disable dotenv358~~~~~~~~~~~~~~359360The ``flask`` command will show a message if it detects dotenv files but361python-dotenv is not installed.362363.. code-block:: bash364365 $ flask run366 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.367368You can tell Flask not to load dotenv files even when python-dotenv is369installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.370This can be useful if you want to load them manually, or if you're using371a project runner that loads them already. Keep in mind that the372environment variables must be set before the app loads or it won't373configure as expected.374375.. tabs::376377 .. group-tab:: Bash378379 .. code-block:: text380381 $ export FLASK_SKIP_DOTENV=1382 $ flask run383384 .. group-tab:: Fish385386 .. code-block:: text387388 $ set -x FLASK_SKIP_DOTENV 1389 $ flask run390391 .. group-tab:: CMD392393 .. code-block:: text394395 > set FLASK_SKIP_DOTENV=1396 > flask run397398 .. group-tab:: Powershell399400 .. code-block:: text401402 > $env:FLASK_SKIP_DOTENV = 1403 > flask run404405406Environment Variables From virtualenv407-------------------------------------408409If you do not want to install dotenv support, you can still set environment410variables by adding them to the end of the virtualenv's :file:`activate`411script. Activating the virtualenv will set the variables.412413.. tabs::414415 .. group-tab:: Bash416417 Unix Bash, :file:`venv/bin/activate`::418419 $ export FLASK_APP=hello420421 .. group-tab:: Fish422423 Fish, :file:`venv/bin/activate.fish`::424425 $ set -x FLASK_APP hello426427 .. group-tab:: CMD428429 Windows CMD, :file:`venv\\Scripts\\activate.bat`::430431 > set FLASK_APP=hello432433 .. group-tab:: Powershell434435 Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::436437 > $env:FLASK_APP = "hello"438439It is preferred to use dotenv support over this, since :file:`.flaskenv` can be440committed to the repository so that it works automatically wherever the project441is checked out.442443444Custom Commands445---------------446447The ``flask`` command is implemented using `Click`_. See that project's448documentation for full information about writing commands.449450This example adds the command ``create-user`` that takes the argument451``name``. ::452453 import click454 from flask import Flask455456 app = Flask(__name__)457458 @app.cli.command("create-user")459 @click.argument("name")460 def create_user(name):461 ...462463::464465 $ flask create-user admin466467This example adds the same command, but as ``user create``, a command in a468group. This is useful if you want to organize multiple related commands. ::469470 import click471 from flask import Flask472 from flask.cli import AppGroup473474 app = Flask(__name__)475 user_cli = AppGroup('user')476477 @user_cli.command('create')478 @click.argument('name')479 def create_user(name):480 ...481482 app.cli.add_command(user_cli)483484::485486 $ flask user create demo487488See :ref:`testing-cli` for an overview of how to test your custom489commands.490491492Registering Commands with Blueprints493~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~494495If your application uses blueprints, you can optionally register CLI496commands directly onto them. When your blueprint is registered onto your497application, the associated commands will be available to the ``flask``498command. By default, those commands will be nested in a group matching499the name of the blueprint.500501.. code-block:: python502503 from flask import Blueprint504505 bp = Blueprint('students', __name__)506507 @bp.cli.command('create')508 @click.argument('name')509 def create(name):510 ...511512 app.register_blueprint(bp)513514.. code-block:: text515516 $ flask students create alice517518You can alter the group name by specifying the ``cli_group`` parameter519when creating the :class:`Blueprint` object, or later with520:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.521The following are equivalent:522523.. code-block:: python524525 bp = Blueprint('students', __name__, cli_group='other')526 # or527 app.register_blueprint(bp, cli_group='other')528529.. code-block:: text530531 $ flask other create alice532533Specifying ``cli_group=None`` will remove the nesting and merge the534commands directly to the application's level:535536.. code-block:: python537538 bp = Blueprint('students', __name__, cli_group=None)539 # or540 app.register_blueprint(bp, cli_group=None)541542.. code-block:: text543544 $ flask create alice545546547Application Context548~~~~~~~~~~~~~~~~~~~549550Commands added using the Flask app's :attr:`~Flask.cli`551:meth:`~cli.AppGroup.command` decorator will be executed with an application552context pushed, so your command and extensions have access to the app and its553configuration. If you create a command using the Click :func:`~click.command`554decorator instead of the Flask decorator, you can use555:func:`~cli.with_appcontext` to get the same behavior. ::556557 import click558 from flask.cli import with_appcontext559560 @click.command()561 @with_appcontext562 def do_work():563 ...564565 app.cli.add_command(do_work)566567If you're sure a command doesn't need the context, you can disable it::568569 @app.cli.command(with_appcontext=False)570 def do_work():571 ...572573574Plugins575-------576577Flask will automatically load commands specified in the ``flask.commands``578`entry point`_. This is useful for extensions that want to add commands when579they are installed. Entry points are specified in :file:`setup.py` ::580581 from setuptools import setup582583 setup(584 name='flask-my-extension',585 ...,586 entry_points={587 'flask.commands': [588 'my-command=flask_my_extension.commands:cli'589 ],590 },591 )592593594.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points595596Inside :file:`flask_my_extension/commands.py` you can then export a Click597object::598599 import click600601 @click.command()602 def cli():603 ...604605Once that package is installed in the same virtualenv as your Flask project,606you can run ``flask my-command`` to invoke the command.607608609.. _custom-scripts:610611Custom Scripts612--------------613614When you are using the app factory pattern, it may be more convenient to define615your own Click script. Instead of using ``FLASK_APP`` and letting Flask load616your application, you can create your own Click object and export it as a617`console script`_ entry point.618619Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::620621 import click622 from flask import Flask623 from flask.cli import FlaskGroup624625 def create_app():626 app = Flask('wiki')627 # other setup628 return app629630 @click.group(cls=FlaskGroup, create_app=create_app)631 def cli():632 """Management script for the Wiki application."""633634Define the entry point in :file:`setup.py`::635636 from setuptools import setup637638 setup(639 name='flask-my-extension',640 ...,641 entry_points={642 'console_scripts': [643 'wiki=wiki:cli'644 ],645 },646 )647648Install the application in the virtualenv in editable mode and the custom649script is available. Note that you don't need to set ``FLASK_APP``. ::650651 $ pip install -e .652 $ wiki run653654.. admonition:: Errors in Custom Scripts655656 When using a custom script, if you introduce an error in your657 module-level code, the reloader will fail because it can no longer658 load the entry point.659660 The ``flask`` command, being separate from your code, does not have661 this issue and is recommended in most cases.662663.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts664665666PyCharm Integration667-------------------668669PyCharm Professional provides a special Flask run configuration. For670the Community Edition, we need to configure it to call the ``flask run``671CLI command with the correct environment variables. These instructions672should be similar for any other IDE you might want to use.673674In PyCharm, with your project open, click on *Run* from the menu bar and675go to *Edit Configurations*. You'll be greeted by a screen similar to676this:677678.. image:: _static/pycharm-runconfig.png679 :align: center680 :class: screenshot681 :alt: Screenshot of PyCharms's run configuration settings.682683There's quite a few options to change, but once we've done it for one684command, we can easily copy the entire configuration and make a single685tweak to give us access to other commands, including any custom ones you686may implement yourself.687688Click the + (*Add New Configuration*) button and select *Python*. Give689the configuration a name such as "flask run". For the ``flask run``690command, check "Single instance only" since you can't run the server691more than once at the same time.692693Select *Module name* from the dropdown (**A**) then input ``flask``.694695The *Parameters* field (**B**) is set to the CLI command to execute696(with any arguments). In this example we use ``run``, which will run697the development server.698699You can skip this next step if you're using :ref:`dotenv`. We need to700add an environment variable (**C**) to identify our application. Click701on the browse button and add an entry with ``FLASK_APP`` on the left and702the Python import or file on the right (``hello`` for example). Add an703entry with ``FLASK_ENV`` and set it to ``development``.704705Next we need to set the working directory (**D**) to be the folder where706our application resides.707708If you have installed your project as a package in your virtualenv, you709may untick the *PYTHONPATH* options (**E**). This will more accurately710match how you deploy the app later.711712Click *Apply* to save the configuration, or *OK* to save and close the713window. Select the configuration in the main PyCharm window and click714the play button next to it to run the server.715716Now that we have a configuration which runs ``flask run`` from within717PyCharm, we can copy that configuration and alter the *Script* argument718to run a different CLI command, e.g. ``flask shell``.