cli.rst
This file
Path
docs/cli.rst
654 lines · 18.8 KiB
Last changed by
Merge pull request #3999 from greyli/improve-cli-docsDavid Lordbefore adoption28262c3
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:: CMD3132 .. code-block:: text3334 > set FLASK_APP=hello35 > flask run3637 .. group-tab:: Powershell3839 .. code-block:: text4041 > $env:FLASK_APP = "hello"42 > flask run4344While ``FLASK_APP`` supports a variety of options for specifying your45application, most use cases should be simple. Here are the typical values:4647(nothing)48 The name "app" or "wsgi" is imported (as a ".py" file, or package),49 automatically detecting an app (``app`` or ``application``) or50 factory (``create_app`` or ``make_app``).5152``FLASK_APP=hello``53 The given name is imported, automatically detecting an app (``app``54 or ``application``) or factory (``create_app`` or ``make_app``).5556----5758``FLASK_APP`` has three parts: an optional path that sets the current working59directory, a Python file or dotted import path, and an optional variable60name of the instance or factory. If the name is a factory, it can optionally61be followed by arguments in parentheses. The following values demonstrate these62parts:6364``FLASK_APP=src/hello``65 Sets the current working directory to ``src`` then imports ``hello``.6667``FLASK_APP=hello.web``68 Imports the path ``hello.web``.6970``FLASK_APP=hello:app2``71 Uses the ``app2`` Flask instance in ``hello``.7273``FLASK_APP="hello:create_app('dev')"``74 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``75 as the argument.7677If ``FLASK_APP`` is not set, the command will try to import "app" or78"wsgi" (as a ".py" file, or package) and try to detect an application79instance or factory.8081Within the given import, the command looks for an application instance named82``app`` or ``application``, then any application instance. If no instance is83found, the command looks for a factory function named ``create_app`` or84``make_app`` that returns an instance.8586If parentheses follow the factory name, their contents are parsed as87Python literals and passed as arguments and keyword arguments to the88function. This means that strings must still be in quotes.899091Run the Development Server92--------------------------9394The :func:`run <cli.run_command>` command will start the development server. It95replaces the :meth:`Flask.run` method in most cases. ::9697 $ flask run98 * Serving Flask app "hello"99 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)100101.. warning:: Do not use this command to run your application in production.102 Only use the development server during development. The development server103 is provided for convenience, but is not designed to be particularly secure,104 stable, or efficient. See :doc:`/deploying/index` for how to run in production.105106107Open a Shell108------------109110To explore the data in your application, you can start an interactive Python111shell with the :func:`shell <cli.shell_command>` command. An application112context will be active, and the app instance will be imported. ::113114 $ flask shell115 Python 3.6.2 (default, Jul 20 2017, 03:52:27)116 [GCC 7.1.1 20170630] on linux117 App: example118 Instance: /home/user/Projects/hello/instance119 >>>120121Use :meth:`~Flask.shell_context_processor` to add other automatic imports.122123124Environments125------------126127.. versionadded:: 1.0128129The environment in which the Flask app runs is set by the130:envvar:`FLASK_ENV` environment variable. If not set it defaults to131``production``. The other recognized environment is ``development``.132Flask and extensions may choose to enable behaviors based on the133environment.134135If the env is set to ``development``, the ``flask`` command will enable136debug mode and ``flask run`` will enable the interactive debugger and137reloader.138139.. tabs::140141 .. group-tab:: Bash142143 .. code-block:: text144145 $ export FLASK_ENV=development146 $ flask run147 * Serving Flask app "hello"148 * Environment: development149 * Debug mode: on150 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)151 * Restarting with inotify reloader152 * Debugger is active!153 * Debugger PIN: 223-456-919154155 .. group-tab:: CMD156157 .. code-block:: text158159 > set FLASK_ENV=development160 > flask run161 * Serving Flask app "hello"162 * Environment: development163 * Debug mode: on164 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)165 * Restarting with inotify reloader166 * Debugger is active!167 * Debugger PIN: 223-456-919168169 .. group-tab:: Powershell170171 .. code-block:: text172173 > $env:FLASK_ENV = "development"174 > flask run175 * Serving Flask app "hello"176 * Environment: development177 * Debug mode: on178 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)179 * Restarting with inotify reloader180 * Debugger is active!181 * Debugger PIN: 223-456-919182183184Watch Extra Files with the Reloader185~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~186187When using development mode, the reloader will trigger whenever your188Python code or imported modules change. The reloader can watch189additional files with the ``--extra-files`` option, or the190``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are191separated with ``:``, or ``;`` on Windows.192193.. tabs::194195 .. group-tab:: Bash196197 .. code-block:: text198199 $ flask run --extra-files file1:dirA/file2:dirB/200 # or201 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/202 $ flask run203 * Running on http://127.0.0.1:8000/204 * Detected change in '/path/to/file1', reloading205206 .. group-tab:: CMD207208 .. code-block:: text209210 > flask run --extra-files file1:dirA/file2:dirB/211 # or212 > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/213 > flask run214 * Running on http://127.0.0.1:8000/215 * Detected change in '/path/to/file1', reloading216217 .. group-tab:: Powershell218219 .. code-block:: text220221 > flask run --extra-files file1:dirA/file2:dirB/222 # or223 > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"224 > flask run225 * Running on http://127.0.0.1:8000/226 * Detected change in '/path/to/file1', reloading227228229Debug Mode230----------231232Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,233as described above. If you want to control debug mode separately, use234:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.235236237.. _dotenv:238239Environment Variables From dotenv240---------------------------------241242Rather than setting ``FLASK_APP`` each time you open a new terminal, you can243use Flask's dotenv support to set environment variables automatically.244245If `python-dotenv`_ is installed, running the ``flask`` command will set246environment variables defined in the files :file:`.env` and :file:`.flaskenv`.247This can be used to avoid having to set ``FLASK_APP`` manually every time you248open a new terminal, and to set configuration using environment variables249similar to how some deployment services work.250251Variables set on the command line are used over those set in :file:`.env`,252which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be253used for public variables, such as ``FLASK_APP``, while :file:`.env` should not254be committed to your repository so that it can set private variables.255256Directories are scanned upwards from the directory you call ``flask``257from to locate the files. The current working directory will be set to the258location of the file, with the assumption that that is the top level project259directory.260261The files are only loaded by the ``flask`` command or calling262:meth:`~Flask.run`. If you would like to load these files when running in263production, you should call :func:`~cli.load_dotenv` manually.264265.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme266267268Setting Command Options269~~~~~~~~~~~~~~~~~~~~~~~270271Click is configured to load default values for command options from272environment variables. The variables use the pattern273``FLASK_COMMAND_OPTION``. For example, to set the port for the run274command, instead of ``flask run --port 8000``:275276.. tabs::277278 .. group-tab:: Bash279280 .. code-block:: text281282 $ export FLASK_RUN_PORT=8000283 $ flask run284 * Running on http://127.0.0.1:8000/285286 .. group-tab:: CMD287288 .. code-block:: text289290 > set FLASK_RUN_PORT=8000291 > flask run292 * Running on http://127.0.0.1:8000/293294 .. group-tab:: Powershell295296 .. code-block:: text297298 > $env:FLASK_RUN_PORT = 8000299 > flask run300 * Running on http://127.0.0.1:8000/301302These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to303control default command options.304305306Disable dotenv307~~~~~~~~~~~~~~308309The ``flask`` command will show a message if it detects dotenv files but310python-dotenv is not installed.311312.. code-block:: bash313314 $ flask run315 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.316317You can tell Flask not to load dotenv files even when python-dotenv is318installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.319This can be useful if you want to load them manually, or if you're using320a project runner that loads them already. Keep in mind that the321environment variables must be set before the app loads or it won't322configure as expected.323324.. tabs::325326 .. group-tab:: Bash327328 .. code-block:: text329330 $ export FLASK_SKIP_DOTENV=1331 $ flask run332333 .. group-tab:: CMD334335 .. code-block:: text336337 > set FLASK_SKIP_DOTENV=1338 > flask run339340 .. group-tab:: Powershell341342 .. code-block:: text343344 > $env:FLASK_SKIP_DOTENV = 1345 > flask run346347348Environment Variables From virtualenv349-------------------------------------350351If you do not want to install dotenv support, you can still set environment352variables by adding them to the end of the virtualenv's :file:`activate`353script. Activating the virtualenv will set the variables.354355.. tabs::356357 .. group-tab:: Bash358359 Unix Bash, :file:`venv/bin/activate`::360361 $ export FLASK_APP=hello362363 .. group-tab:: CMD364365 Windows CMD, :file:`venv\\Scripts\\activate.bat`::366367 > set FLASK_APP=hello368369 .. group-tab:: Powershell370371 Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::372373 > $env:FLASK_APP = "hello"374375It is preferred to use dotenv support over this, since :file:`.flaskenv` can be376committed to the repository so that it works automatically wherever the project377is checked out.378379380Custom Commands381---------------382383The ``flask`` command is implemented using `Click`_. See that project's384documentation for full information about writing commands.385386This example adds the command ``create-user`` that takes the argument387``name``. ::388389 import click390 from flask import Flask391392 app = Flask(__name__)393394 @app.cli.command("create-user")395 @click.argument("name")396 def create_user(name):397 ...398399::400401 $ flask create-user admin402403This example adds the same command, but as ``user create``, a command in a404group. This is useful if you want to organize multiple related commands. ::405406 import click407 from flask import Flask408 from flask.cli import AppGroup409410 app = Flask(__name__)411 user_cli = AppGroup('user')412413 @user_cli.command('create')414 @click.argument('name')415 def create_user(name):416 ...417418 app.cli.add_command(user_cli)419420::421422 $ flask user create demo423424See :ref:`testing-cli` for an overview of how to test your custom425commands.426427428Registering Commands with Blueprints429~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~430431If your application uses blueprints, you can optionally register CLI432commands directly onto them. When your blueprint is registered onto your433application, the associated commands will be available to the ``flask``434command. By default, those commands will be nested in a group matching435the name of the blueprint.436437.. code-block:: python438439 from flask import Blueprint440441 bp = Blueprint('students', __name__)442443 @bp.cli.command('create')444 @click.argument('name')445 def create(name):446 ...447448 app.register_blueprint(bp)449450.. code-block:: text451452 $ flask students create alice453454You can alter the group name by specifying the ``cli_group`` parameter455when creating the :class:`Blueprint` object, or later with456:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.457The following are equivalent:458459.. code-block:: python460461 bp = Blueprint('students', __name__, cli_group='other')462 # or463 app.register_blueprint(bp, cli_group='other')464465.. code-block:: text466467 $ flask other create alice468469Specifying ``cli_group=None`` will remove the nesting and merge the470commands directly to the application's level:471472.. code-block:: python473474 bp = Blueprint('students', __name__, cli_group=None)475 # or476 app.register_blueprint(bp, cli_group=None)477478.. code-block:: text479480 $ flask create alice481482483Application Context484~~~~~~~~~~~~~~~~~~~485486Commands added using the Flask app's :attr:`~Flask.cli`487:meth:`~cli.AppGroup.command` decorator will be executed with an application488context pushed, so your command and extensions have access to the app and its489configuration. If you create a command using the Click :func:`~click.command`490decorator instead of the Flask decorator, you can use491:func:`~cli.with_appcontext` to get the same behavior. ::492493 import click494 from flask.cli import with_appcontext495496 @click.command()497 @with_appcontext498 def do_work():499 ...500501 app.cli.add_command(do_work)502503If you're sure a command doesn't need the context, you can disable it::504505 @app.cli.command(with_appcontext=False)506 def do_work():507 ...508509510Plugins511-------512513Flask will automatically load commands specified in the ``flask.commands``514`entry point`_. This is useful for extensions that want to add commands when515they are installed. Entry points are specified in :file:`setup.py` ::516517 from setuptools import setup518519 setup(520 name='flask-my-extension',521 ...,522 entry_points={523 'flask.commands': [524 'my-command=flask_my_extension.commands:cli'525 ],526 },527 )528529530.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points531532Inside :file:`flask_my_extension/commands.py` you can then export a Click533object::534535 import click536537 @click.command()538 def cli():539 ...540541Once that package is installed in the same virtualenv as your Flask project,542you can run ``flask my-command`` to invoke the command.543544545.. _custom-scripts:546547Custom Scripts548--------------549550When you are using the app factory pattern, it may be more convenient to define551your own Click script. Instead of using ``FLASK_APP`` and letting Flask load552your application, you can create your own Click object and export it as a553`console script`_ entry point.554555Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::556557 import click558 from flask import Flask559 from flask.cli import FlaskGroup560561 def create_app():562 app = Flask('wiki')563 # other setup564 return app565566 @click.group(cls=FlaskGroup, create_app=create_app)567 def cli():568 """Management script for the Wiki application."""569570Define the entry point in :file:`setup.py`::571572 from setuptools import setup573574 setup(575 name='flask-my-extension',576 ...,577 entry_points={578 'console_scripts': [579 'wiki=wiki:cli'580 ],581 },582 )583584Install the application in the virtualenv in editable mode and the custom585script is available. Note that you don't need to set ``FLASK_APP``. ::586587 $ pip install -e .588 $ wiki run589590.. admonition:: Errors in Custom Scripts591592 When using a custom script, if you introduce an error in your593 module-level code, the reloader will fail because it can no longer594 load the entry point.595596 The ``flask`` command, being separate from your code, does not have597 this issue and is recommended in most cases.598599.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts600601602PyCharm Integration603-------------------604605PyCharm Professional provides a special Flask run configuration. For606the Community Edition, we need to configure it to call the ``flask run``607CLI command with the correct environment variables. These instructions608should be similar for any other IDE you might want to use.609610In PyCharm, with your project open, click on *Run* from the menu bar and611go to *Edit Configurations*. You'll be greeted by a screen similar to612this:613614.. image:: _static/pycharm-runconfig.png615 :align: center616 :class: screenshot617 :alt: Screenshot of PyCharms's run configuration settings.618619There's quite a few options to change, but once we've done it for one620command, we can easily copy the entire configuration and make a single621tweak to give us access to other commands, including any custom ones you622may implement yourself.623624Click the + (*Add New Configuration*) button and select *Python*. Give625the configuration a name such as "flask run". For the ``flask run``626command, check "Single instance only" since you can't run the server627more than once at the same time.628629Select *Module name* from the dropdown (**A**) then input ``flask``.630631The *Parameters* field (**B**) is set to the CLI command to execute632(with any arguments). In this example we use ``run``, which will run633the development server.634635You can skip this next step if you're using :ref:`dotenv`. We need to636add an environment variable (**C**) to identify our application. Click637on the browse button and add an entry with ``FLASK_APP`` on the left and638the Python import or file on the right (``hello`` for example). Add an639entry with ``FLASK_ENV`` and set it to ``development``.640641Next we need to set the working directory (**D**) to be the folder where642our application resides.643644If you have installed your project as a package in your virtualenv, you645may untick the *PYTHONPATH* options (**E**). This will more accurately646match how you deploy the app later.647648Click *Apply* to save the configuration, or *OK* to save and close the649window. Select the configuration in the main PyCharm window and click650the play button next to it to run the server.651652Now that we have a configuration which runs ``flask run`` from within653PyCharm, we can copy that configuration and alter the *Script* argument654to run a different CLI command, e.g. ``flask shell``.