cli.rst
This file
Path
docs/cli.rst
563 lines · 16.3 KiB
Last changed by
Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
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 ``--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 --debug run99 * 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-919105106107Watch and Ignore Files with the Reloader108~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~109110When using debug mode, the reloader will trigger whenever your Python code or imported111modules change. The reloader can watch additional files with the ``--extra-files``112option. Multiple paths are separated with ``:``, or ``;`` on Windows.113114.. code-block:: text115116 $ flask run --extra-files file1:dirA/file2:dirB/117 * Running on http://127.0.0.1:8000/118 * Detected change in '/path/to/file1', reloading119120The reloader can also ignore files using :mod:`fnmatch` patterns with the121``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on122Windows.123124125Open a Shell126------------127128To explore the data in your application, you can start an interactive Python129shell with the :func:`shell <cli.shell_command>` command. An application130context will be active, and the app instance will be imported. ::131132 $ flask shell133 Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux134 App: example [production]135 Instance: /home/david/Projects/pallets/flask/instance136 >>>137138Use :meth:`~Flask.shell_context_processor` to add other automatic imports.139140141.. _dotenv:142143Environment Variables From dotenv144---------------------------------145146The ``flask`` command supports setting any option for any command with147environment variables. The variables are named like ``FLASK_OPTION`` or148``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or149``FLASK_RUN_PORT``.150151Rather than passing options every time you run a command, or environment152variables every time you open a new terminal, you can use Flask's dotenv153support to set environment variables automatically.154155If `python-dotenv`_ is installed, running the ``flask`` command will set156environment variables defined in the files ``.env`` and ``.flaskenv``.157You can also specify an extra file to load with the ``--env-file``158option. Dotenv files can be used to avoid having to set ``--app`` or159``FLASK_APP`` manually, and to set configuration using environment160variables similar to how some deployment services work.161162Variables set on the command line are used over those set in :file:`.env`,163which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be164used for public variables, such as ``FLASK_APP``, while :file:`.env` should not165be committed to your repository so that it can set private variables.166167Directories are scanned upwards from the directory you call ``flask``168from to locate the files.169170The files are only loaded by the ``flask`` command or calling171:meth:`~Flask.run`. If you would like to load these files when running in172production, you should call :func:`~cli.load_dotenv` manually.173174.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme175176177Setting Command Options178~~~~~~~~~~~~~~~~~~~~~~~179180Click is configured to load default values for command options from181environment variables. The variables use the pattern182``FLASK_COMMAND_OPTION``. For example, to set the port for the run183command, instead of ``flask run --port 8000``:184185.. tabs::186187 .. group-tab:: Bash188189 .. code-block:: text190191 $ export FLASK_RUN_PORT=8000192 $ flask run193 * Running on http://127.0.0.1:8000/194195 .. group-tab:: Fish196197 .. code-block:: text198199 $ set -x FLASK_RUN_PORT 8000200 $ flask run201 * Running on http://127.0.0.1:8000/202203 .. group-tab:: CMD204205 .. code-block:: text206207 > set FLASK_RUN_PORT=8000208 > flask run209 * Running on http://127.0.0.1:8000/210211 .. group-tab:: Powershell212213 .. code-block:: text214215 > $env:FLASK_RUN_PORT = 8000216 > flask run217 * Running on http://127.0.0.1:8000/218219These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to220control default command options.221222223Disable dotenv224~~~~~~~~~~~~~~225226The ``flask`` command will show a message if it detects dotenv files but227python-dotenv is not installed.228229.. code-block:: bash230231 $ flask run232 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.233234You can tell Flask not to load dotenv files even when python-dotenv is235installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.236This can be useful if you want to load them manually, or if you're using237a project runner that loads them already. Keep in mind that the238environment variables must be set before the app loads or it won't239configure as expected.240241.. tabs::242243 .. group-tab:: Bash244245 .. code-block:: text246247 $ export FLASK_SKIP_DOTENV=1248 $ flask run249250 .. group-tab:: Fish251252 .. code-block:: text253254 $ set -x FLASK_SKIP_DOTENV 1255 $ flask run256257 .. group-tab:: CMD258259 .. code-block:: text260261 > set FLASK_SKIP_DOTENV=1262 > flask run263264 .. group-tab:: Powershell265266 .. code-block:: text267268 > $env:FLASK_SKIP_DOTENV = 1269 > flask run270271272Environment Variables From virtualenv273-------------------------------------274275If you do not want to install dotenv support, you can still set environment276variables by adding them to the end of the virtualenv's :file:`activate`277script. Activating the virtualenv will set the variables.278279.. tabs::280281 .. group-tab:: Bash282283 Unix Bash, :file:`venv/bin/activate`::284285 $ export FLASK_APP=hello286287 .. group-tab:: Fish288289 Fish, :file:`venv/bin/activate.fish`::290291 $ set -x FLASK_APP hello292293 .. group-tab:: CMD294295 Windows CMD, :file:`venv\\Scripts\\activate.bat`::296297 > set FLASK_APP=hello298299 .. group-tab:: Powershell300301 Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::302303 > $env:FLASK_APP = "hello"304305It is preferred to use dotenv support over this, since :file:`.flaskenv` can be306committed to the repository so that it works automatically wherever the project307is checked out.308309310Custom Commands311---------------312313The ``flask`` command is implemented using `Click`_. See that project's314documentation for full information about writing commands.315316This example adds the command ``create-user`` that takes the argument317``name``. ::318319 import click320 from flask import Flask321322 app = Flask(__name__)323324 @app.cli.command("create-user")325 @click.argument("name")326 def create_user(name):327 ...328329::330331 $ flask create-user admin332333This example adds the same command, but as ``user create``, a command in a334group. This is useful if you want to organize multiple related commands. ::335336 import click337 from flask import Flask338 from flask.cli import AppGroup339340 app = Flask(__name__)341 user_cli = AppGroup('user')342343 @user_cli.command('create')344 @click.argument('name')345 def create_user(name):346 ...347348 app.cli.add_command(user_cli)349350::351352 $ flask user create demo353354See :ref:`testing-cli` for an overview of how to test your custom355commands.356357358Registering Commands with Blueprints359~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~360361If your application uses blueprints, you can optionally register CLI362commands directly onto them. When your blueprint is registered onto your363application, the associated commands will be available to the ``flask``364command. By default, those commands will be nested in a group matching365the name of the blueprint.366367.. code-block:: python368369 from flask import Blueprint370371 bp = Blueprint('students', __name__)372373 @bp.cli.command('create')374 @click.argument('name')375 def create(name):376 ...377378 app.register_blueprint(bp)379380.. code-block:: text381382 $ flask students create alice383384You can alter the group name by specifying the ``cli_group`` parameter385when creating the :class:`Blueprint` object, or later with386:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.387The following are equivalent:388389.. code-block:: python390391 bp = Blueprint('students', __name__, cli_group='other')392 # or393 app.register_blueprint(bp, cli_group='other')394395.. code-block:: text396397 $ flask other create alice398399Specifying ``cli_group=None`` will remove the nesting and merge the400commands directly to the application's level:401402.. code-block:: python403404 bp = Blueprint('students', __name__, cli_group=None)405 # or406 app.register_blueprint(bp, cli_group=None)407408.. code-block:: text409410 $ flask create alice411412413Application Context414~~~~~~~~~~~~~~~~~~~415416Commands added using the Flask app's :attr:`~Flask.cli` or417:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator418will be executed with an application context pushed, so your custom419commands and parameters have access to the app and its configuration. The420:func:`~cli.with_appcontext` decorator can be used to get the same421behavior, but is not needed in most cases.422423.. code-block:: python424425 import click426 from flask.cli import with_appcontext427428 @click.command()429 @with_appcontext430 def do_work():431 ...432433 app.cli.add_command(do_work)434435436Plugins437-------438439Flask will automatically load commands specified in the ``flask.commands``440`entry point`_. This is useful for extensions that want to add commands when441they are installed. Entry points are specified in :file:`setup.py` ::442443 from setuptools import setup444445 setup(446 name='flask-my-extension',447 ...,448 entry_points={449 'flask.commands': [450 'my-command=flask_my_extension.commands:cli'451 ],452 },453 )454455456.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points457458Inside :file:`flask_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:`setup.py`::497498 from setuptools import setup499500 setup(501 name='flask-my-extension',502 ...,503 entry_points={504 'console_scripts': [505 'wiki=wiki:cli'506 ],507 },508 )509510Install the application in the virtualenv in editable mode and the custom511script is available. Note that you don't need to set ``--app``. ::512513 $ pip install -e .514 $ wiki run515516.. admonition:: Errors in Custom Scripts517518 When using a custom script, if you introduce an error in your519 module-level code, the reloader will fail because it can no longer520 load the entry point.521522 The ``flask`` command, being separate from your code, does not have523 this issue and is recommended in most cases.524525.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts526527528PyCharm Integration529-------------------530531PyCharm Professional provides a special Flask run configuration to run the development532server. For the Community Edition, and for other commands besides ``run``, you need to533create a custom run configuration. These instructions should be similar for any other534IDE you use.535536In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit537Configurations*. You'll see a screen similar to this:538539.. image:: _static/pycharm-run-config.png540 :align: center541 :class: screenshot542 :alt: Screenshot of PyCharm run configuration.543544Once you create a configuration for the ``flask run``, you can copy and change it to545call any other command.546547Click the *+ (Add New Configuration)* button and select *Python*. Give the configuration548a name such as "flask run".549550Click the *Script path* dropdown and change it to *Module name*, then input ``flask``.551552The *Parameters* field is set to the CLI command to execute along with any arguments.553This example uses ``--app hello --debug run``, which will run the development server in554debug mode. ``--app hello`` should be the import or file with your Flask app.555556If you installed your project as a package in your virtualenv, you may uncheck the557*PYTHONPATH* options. This will more accurately match how you deploy later.558559Click *OK* to save and close the configuration. Select the configuration in the main560PyCharm window and click the play button next to it to run the server.561562Now that you have a configuration for ``flask run``, you can copy that configuration and563change the *Parameters* argument to run a different CLI command.