cli.rst
This file
Path
docs/cli.rst
537 lines · 16.2 KiB
Last changed by
Merge pull request #3564 from pallets/cli-ast-parseDavid Lordbefore adoption2062d98
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.2021Unix Bash (Linux, Mac, etc.)::2223 $ export FLASK_APP=hello24 $ flask run2526Windows CMD::2728 > set FLASK_APP=hello29 > flask run3031Windows PowerShell::3233 > $env:FLASK_APP = "hello"34 > flask run3536While ``FLASK_APP`` supports a variety of options for specifying your37application, most use cases should be simple. Here are the typical values:3839(nothing)40 The file :file:`wsgi.py` is imported, automatically detecting an app41 (``app``). This provides an easy way to create an app from a factory with42 extra arguments.4344``FLASK_APP=hello``45 The name is imported, automatically detecting an app (``app``) or factory46 (``create_app``).4748----4950``FLASK_APP`` has three parts: an optional path that sets the current working51directory, a Python file or dotted import path, and an optional variable52name of the instance or factory. If the name is a factory, it can optionally53be followed by arguments in parentheses. The following values demonstrate these54parts:5556``FLASK_APP=src/hello``57 Sets the current working directory to ``src`` then imports ``hello``.5859``FLASK_APP=hello.web``60 Imports the path ``hello.web``.6162``FLASK_APP=hello:app2``63 Uses the ``app2`` Flask instance in ``hello``.6465``FLASK_APP="hello:create_app('dev')"``66 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``67 as the argument.6869If ``FLASK_APP`` is not set, the command will try to import "app" or70"wsgi" (as a ".py" file, or package) and try to detect an application71instance or factory.7273Within the given import, the command looks for an application instance named74``app`` or ``application``, then any application instance. If no instance is75found, the command looks for a factory function named ``create_app`` or76``make_app`` that returns an instance.7778If parentheses follow the factory name, their contents are parsed as79Python literals and passed as arguments and keyword arguments to the80function. This means that strings must still be in quotes.818283Run the Development Server84--------------------------8586The :func:`run <cli.run_command>` command will start the development server. It87replaces the :meth:`Flask.run` method in most cases. ::8889 $ flask run90 * Serving Flask app "hello"91 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)9293.. warning:: Do not use this command to run your application in production.94 Only use the development server during development. The development server95 is provided for convenience, but is not designed to be particularly secure,96 stable, or efficient. See :doc:`/deploying/index` for how to run in production.979899Open a Shell100------------101102To explore the data in your application, you can start an interactive Python103shell with the :func:`shell <cli.shell_command>` command. An application104context will be active, and the app instance will be imported. ::105106 $ flask shell107 Python 3.6.2 (default, Jul 20 2017, 03:52:27)108 [GCC 7.1.1 20170630] on linux109 App: example110 Instance: /home/user/Projects/hello/instance111 >>>112113Use :meth:`~Flask.shell_context_processor` to add other automatic imports.114115116Environments117------------118119.. versionadded:: 1.0120121The environment in which the Flask app runs is set by the122:envvar:`FLASK_ENV` environment variable. If not set it defaults to123``production``. The other recognized environment is ``development``.124Flask and extensions may choose to enable behaviors based on the125environment.126127If the env is set to ``development``, the ``flask`` command will enable128debug mode and ``flask run`` will enable the interactive debugger and129reloader.130131::132133 $ FLASK_ENV=development flask run134 * Serving Flask app "hello"135 * Environment: development136 * Debug mode: on137 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)138 * Restarting with inotify reloader139 * Debugger is active!140 * Debugger PIN: 223-456-919141142143Watch Extra Files with the Reloader144~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~145146When using development mode, the reloader will trigger whenever your147Python code or imported modules change. The reloader can watch148additional files with the ``--extra-files`` option, or the149``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are150separated with ``:``, or ``;`` on Windows.151152.. code-block:: none153154 $ flask run --extra-files file1:dirA/file2:dirB/155 # or156 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/157 $ flask run158 * Running on http://127.0.0.1:8000/159 * Detected change in '/path/to/file1', reloading160161162Debug Mode163----------164165Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,166as described above. If you want to control debug mode separately, use167:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.168169170.. _dotenv:171172Environment Variables From dotenv173---------------------------------174175Rather than setting ``FLASK_APP`` each time you open a new terminal, you can176use Flask's dotenv support to set environment variables automatically.177178If `python-dotenv`_ is installed, running the ``flask`` command will set179environment variables defined in the files :file:`.env` and :file:`.flaskenv`.180This can be used to avoid having to set ``FLASK_APP`` manually every time you181open a new terminal, and to set configuration using environment variables182similar to how some deployment services work.183184Variables set on the command line are used over those set in :file:`.env`,185which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be186used for public variables, such as ``FLASK_APP``, while :file:`.env` should not187be committed to your repository so that it can set private variables.188189Directories are scanned upwards from the directory you call ``flask``190from to locate the files. The current working directory will be set to the191location of the file, with the assumption that that is the top level project192directory.193194The 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.. code-block:: bash210211 $ export FLASK_RUN_PORT=8000212 $ flask run213 * Running on http://127.0.0.1:8000/214215These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to216control default command options.217218219Disable dotenv220~~~~~~~~~~~~~~221222The ``flask`` command will show a message if it detects dotenv files but223python-dotenv is not installed.224225.. code-block:: bash226227 $ flask run228 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.229230You can tell Flask not to load dotenv files even when python-dotenv is231installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.232This can be useful if you want to load them manually, or if you're using233a project runner that loads them already. Keep in mind that the234environment variables must be set before the app loads or it won't235configure as expected.236237.. code-block:: bash238239 $ export FLASK_SKIP_DOTENV=1240 $ flask run241242243Environment Variables From virtualenv244-------------------------------------245246If you do not want to install dotenv support, you can still set environment247variables by adding them to the end of the virtualenv's :file:`activate`248script. Activating the virtualenv will set the variables.249250Unix Bash, :file:`venv/bin/activate`::251252 $ export FLASK_APP=hello253254Windows CMD, :file:`venv\\Scripts\\activate.bat`::255256 > set FLASK_APP=hello257258It is preferred to use dotenv support over this, since :file:`.flaskenv` can be259committed to the repository so that it works automatically wherever the project260is checked out.261262263Custom Commands264---------------265266The ``flask`` command is implemented using `Click`_. See that project's267documentation for full information about writing commands.268269This example adds the command ``create-user`` that takes the argument270``name``. ::271272 import click273 from flask import Flask274275 app = Flask(__name__)276277 @app.cli.command("create-user")278 @click.argument("name")279 def create_user(name):280 ...281282::283284 $ flask create-user admin285286This example adds the same command, but as ``user create``, a command in a287group. This is useful if you want to organize multiple related commands. ::288289 import click290 from flask import Flask291 from flask.cli import AppGroup292293 app = Flask(__name__)294 user_cli = AppGroup('user')295296 @user_cli.command('create')297 @click.argument('name')298 def create_user(name):299 ...300301 app.cli.add_command(user_cli)302303::304305 $ flask user create demo306307See :ref:`testing-cli` for an overview of how to test your custom308commands.309310311Registering Commands with Blueprints312~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~313314If your application uses blueprints, you can optionally register CLI315commands directly onto them. When your blueprint is registered onto your316application, the associated commands will be available to the ``flask``317command. By default, those commands will be nested in a group matching318the name of the blueprint.319320.. code-block:: python321322 from flask import Blueprint323324 bp = Blueprint('students', __name__)325326 @bp.cli.command('create')327 @click.argument('name')328 def create(name):329 ...330331 app.register_blueprint(bp)332333.. code-block:: text334335 $ flask students create alice336337You can alter the group name by specifying the ``cli_group`` parameter338when creating the :class:`Blueprint` object, or later with339:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.340The following are equivalent:341342.. code-block:: python343344 bp = Blueprint('students', __name__, cli_group='other')345 # or346 app.register_blueprint(bp, cli_group='other')347348.. code-block:: text349350 $ flask other create alice351352Specifying ``cli_group=None`` will remove the nesting and merge the353commands directly to the application's level:354355.. code-block:: python356357 bp = Blueprint('students', __name__, cli_group=None)358 # or359 app.register_blueprint(bp, cli_group=None)360361.. code-block:: text362363 $ flask create alice364365366Application Context367~~~~~~~~~~~~~~~~~~~368369Commands added using the Flask app's :attr:`~Flask.cli`370:meth:`~cli.AppGroup.command` decorator will be executed with an application371context pushed, so your command and extensions have access to the app and its372configuration. If you create a command using the Click :func:`~click.command`373decorator instead of the Flask decorator, you can use374:func:`~cli.with_appcontext` to get the same behavior. ::375376 import click377 from flask.cli import with_appcontext378379 @click.command()380 @with_appcontext381 def do_work():382 ...383384 app.cli.add_command(do_work)385386If you're sure a command doesn't need the context, you can disable it::387388 @app.cli.command(with_appcontext=False)389 def do_work():390 ...391392393Plugins394-------395396Flask will automatically load commands specified in the ``flask.commands``397`entry point`_. This is useful for extensions that want to add commands when398they are installed. Entry points are specified in :file:`setup.py` ::399400 from setuptools import setup401402 setup(403 name='flask-my-extension',404 ...,405 entry_points={406 'flask.commands': [407 'my-command=flask_my_extension.commands:cli'408 ],409 },410 )411412413.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points414415Inside :file:`flask_my_extension/commands.py` you can then export a Click416object::417418 import click419420 @click.command()421 def cli():422 ...423424Once that package is installed in the same virtualenv as your Flask project,425you can run ``flask my-command`` to invoke the command.426427428.. _custom-scripts:429430Custom Scripts431--------------432433When you are using the app factory pattern, it may be more convenient to define434your own Click script. Instead of using ``FLASK_APP`` and letting Flask load435your application, you can create your own Click object and export it as a436`console script`_ entry point.437438Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::439440 import click441 from flask import Flask442 from flask.cli import FlaskGroup443444 def create_app():445 app = Flask('wiki')446 # other setup447 return app448449 @click.group(cls=FlaskGroup, create_app=create_app)450 def cli():451 """Management script for the Wiki application."""452453Define the entry point in :file:`setup.py`::454455 from setuptools import setup456457 setup(458 name='flask-my-extension',459 ...,460 entry_points={461 'console_scripts': [462 'wiki=wiki:cli'463 ],464 },465 )466467Install the application in the virtualenv in editable mode and the custom468script is available. Note that you don't need to set ``FLASK_APP``. ::469470 $ pip install -e .471 $ wiki run472473.. admonition:: Errors in Custom Scripts474475 When using a custom script, if you introduce an error in your476 module-level code, the reloader will fail because it can no longer477 load the entry point.478479 The ``flask`` command, being separate from your code, does not have480 this issue and is recommended in most cases.481482.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts483484485PyCharm Integration486-------------------487488PyCharm Professional provides a special Flask run configuration. For489the Community Edition, we need to configure it to call the ``flask run``490CLI command with the correct environment variables. These instructions491should be similar for any other IDE you might want to use.492493In PyCharm, with your project open, click on *Run* from the menu bar and494go to *Edit Configurations*. You'll be greeted by a screen similar to495this:496497.. image:: _static/pycharm-runconfig.png498 :align: center499 :class: screenshot500 :alt: Screenshot of PyCharms's run configuration settings.501502There's quite a few options to change, but once we've done it for one503command, we can easily copy the entire configuration and make a single504tweak to give us access to other commands, including any custom ones you505may implement yourself.506507Click the + (*Add New Configuration*) button and select *Python*. Give508the configuration a name such as "flask run". For the ``flask run``509command, check "Single instance only" since you can't run the server510more than once at the same time.511512Select *Module name* from the dropdown (**A**) then input ``flask``.513514The *Parameters* field (**B**) is set to the CLI command to execute515(with any arguments). In this example we use ``run``, which will run516the development server.517518You can skip this next step if you're using :ref:`dotenv`. We need to519add an environment variable (**C**) to identify our application. Click520on the browse button and add an entry with ``FLASK_APP`` on the left and521the Python import or file on the right (``hello`` for example). Add an522entry with ``FLASK_ENV`` and set it to ``development``.523524Next we need to set the working directory (**D**) to be the folder where525our application resides.526527If you have installed your project as a package in your virtualenv, you528may untick the *PYTHONPATH* options (**E**). This will more accurately529match how you deploy the app later.530531Click *Apply* to save the configuration, or *OK* to save and close the532window. Select the configuration in the main PyCharm window and click533the play button next to it to run the server.534535Now that we have a configuration which runs ``flask run`` from within536PyCharm, we can copy that configuration and alter the *Script* argument537to run a different CLI command, e.g. ``flask shell``.