Skip to content
Myr

cli.rst

This file

Path

docs/cli.rst

541 lines · 16.5 KiB

Last changed by

remove unused ref directivesDavid Lordbefore adoption171aabc

History of this file

Take it

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

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 1–10why, 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.10

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 11why, one step back
11.. _Click: https://click.palletsprojects.com/

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 12–68why, one step back
12
1314Application 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.68

Merge branch '1.0.x'David Lordbefore adoption2236ba9

lines 69–71why, one step back
69If ``FLASK_APP`` is not set, the command will try to import "app" or
70"wsgi" (as a ".py" file, or package) and try to detect an application71instance or factory.

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 72–78why, one step back
72
73Within 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.7778When calling an application factory, if the factory takes an argument named

Merge pull request #2870 from jerr0328/docs-update-cli-scriptinfoDavid Lordbefore adoption93e4b71

lines 79–84why, one step back
79``script_info``, then the :class:`~cli.ScriptInfo` instance is passed as a
80keyword argument. If the application factory takes only one argument and no81parentheses follow the factory name, the :class:`~cli.ScriptInfo` instance82is passed as a positional argument. If parentheses follow the factory name,83their contents are parsed as Python literals and passes as arguments to the84function. This means that strings must still be in quotes.

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 85–99why, one step back
85
8687Run the Development Server88--------------------------8990The :func:`run <cli.run_command>` command will start the development server. It91replaces the :meth:`Flask.run` method in most cases. ::9293 $ flask run94 * Serving Flask app "hello"95 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)9697.. warning:: Do not use this command to run your application in production.98 Only use the development server during development. The development server99 is provided for convenience, but is not designed to be particularly secure,

remove unused ref directivesDavid Lordbefore adoption171aabc

line 100why, one step back
100 stable, or efficient. See :doc:`/deploying/index` for how to run in production.

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 101–146why, one step back
101
102103Open a Shell104------------105106To explore the data in your application, you can start an interactive Python107shell with the :func:`shell <cli.shell_command>` command. An application108context will be active, and the app instance will be imported. ::109110 $ flask shell111 Python 3.6.2 (default, Jul 20 2017, 03:52:27)112 [GCC 7.1.1 20170630] on linux113 App: example114 Instance: /home/user/Projects/hello/instance115 >>>116117Use :meth:`~Flask.shell_context_processor` to add other automatic imports.118119120Environments121------------122123.. versionadded:: 1.0124125The environment in which the Flask app runs is set by the126:envvar:`FLASK_ENV` environment variable. If not set it defaults to127``production``. The other recognized environment is ``development``.128Flask and extensions may choose to enable behaviors based on the129environment.130131If the env is set to ``development``, the ``flask`` command will enable132debug mode and ``flask run`` will enable the interactive debugger and133reloader.134135::136137 $ FLASK_ENV=development flask run138 * Serving Flask app "hello"139 * Environment: development140 * Debug mode: on141 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)142 * Restarting with inotify reloader143 * Debugger is active!144 * Debugger PIN: 223-456-919145146

Merge pull request #2898 from rochacbruno/2897-Add-Extra-Files-to-CLIDavid Lordbefore adoption2616d97

lines 147–165why, one step back
147Watch Extra Files with the Reloader
148~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~149150When using development mode, the reloader will trigger whenever your151Python code or imported modules change. The reloader can watch152additional files with the ``--extra-files`` option, or the153``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are154separated with ``:``, or ``;`` on Windows.155156.. code-block:: none157158 $ flask run --extra-files file1:dirA/file2:dirB/159 # or160 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/161 $ flask run162 * Running on http://127.0.0.1:8000/163 * Detected change in '/path/to/file1', reloading164165

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 166–204why, one step back
166Debug Mode
167----------168169Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,170as described above. If you want to control debug mode separately, use171:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.172173174.. _dotenv:175176Environment Variables From dotenv177---------------------------------178179Rather than setting ``FLASK_APP`` each time you open a new terminal, you can180use Flask's dotenv support to set environment variables automatically.181182If `python-dotenv`_ is installed, running the ``flask`` command will set183environment variables defined in the files :file:`.env` and :file:`.flaskenv`.184This can be used to avoid having to set ``FLASK_APP`` manually every time you185open a new terminal, and to set configuration using environment variables186similar to how some deployment services work.187188Variables set on the command line are used over those set in :file:`.env`,189which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be190used for public variables, such as ``FLASK_APP``, while :file:`.env` should not191be committed to your repository so that it can set private variables.192193Directories are scanned upwards from the directory you call ``flask``194from to locate the files. The current working directory will be set to the195location of the file, with the assumption that that is the top level project196directory.197198The files are only loaded by the ``flask`` command or calling199:meth:`~Flask.run`. If you would like to load these files when running in200production, you should call :func:`~cli.load_dotenv` manually.201202.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme203204

document cli option env varsDavid Lordbefore adoption93698b5

lines 205–212why, one step back
205Setting Command Options
206~~~~~~~~~~~~~~~~~~~~~~~207208Click is configured to load default values for command options from209environment variables. The variables use the pattern210``FLASK_COMMAND_OPTION``. For example, to set the port for the run211command, instead of ``flask run --port 8000``:212

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

line 213why, one step back
213.. code-block:: bash

document cli option env varsDavid Lordbefore adoption93698b5

line 214why, one step back
214

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

lines 215–216why, one step back
215 $ export FLASK_RUN_PORT=8000
216 $ flask run

document cli option env varsDavid Lordbefore adoption93698b5

lines 217–222why, one step back
217 * Running on http://127.0.0.1:8000/
218219These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to220control default command options.221222

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

lines 223–228why, one step back
223Disable dotenv
224~~~~~~~~~~~~~~225226The ``flask`` command will show a message if it detects dotenv files but227python-dotenv is not installed.228

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

line 229why, one step back
229.. code-block:: bash

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

line 230why, one step back
230

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 231why, one step back
231 $ flask run

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

lines 232–240why, one step back
232 * 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.240

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

line 241why, one step back
241.. code-block:: bash

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

line 242why, one step back
242

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

lines 243–244why, one step back
243 $ export FLASK_SKIP_DOTENV=1
244 $ flask run

Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185

lines 245–246why, one step back
245
246

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 247–255why, one step back
247Environment Variables From virtualenv
248-------------------------------------249250If you do not want to install dotenv support, you can still set environment251variables by adding them to the end of the virtualenv's :file:`activate`252script. Activating the virtualenv will set the variables.253254Unix Bash, :file:`venv/bin/activate`::255

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 256why, one step back
256 $ export FLASK_APP=hello

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 257–259why, one step back
257
258Windows CMD, :file:`venv\\Scripts\\activate.bat`::259

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 260why, one step back
260 > set FLASK_APP=hello

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 261–272why, one step back
261
262It is preferred to use dotenv support over this, since :file:`.flaskenv` can be263committed to the repository so that it works automatically wherever the project264is checked out.265266267Custom Commands268---------------269270The ``flask`` command is implemented using `Click`_. See that project's271documentation for full information about writing commands.272

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 273why, one step back
273This example adds the command ``create-user`` that takes the argument

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 274–280why, one step back
274``name``. ::
275276 import click277 from flask import Flask278279 app = Flask(__name__)280

Merge branch '1.0.x'David Lordbefore adoption1351d0a

lines 281–282why, one step back
281 @app.cli.command("create-user")
282 @click.argument("name")

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 283–287why, one step back
283 def create_user(name):
284 ...285286::287

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 288why, one step back
288 $ flask create-user admin

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 289–308why, one step back
289
290This example adds the same command, but as ``user create``, a command in a291group. This is useful if you want to organize multiple related commands. ::292293 import click294 from flask import Flask295 from flask.cli import AppGroup296297 app = Flask(__name__)298 user_cli = AppGroup('user')299300 @user_cli.command('create')301 @click.argument('name')302 def create_user(name):303 ...304305 app.cli.add_command(user_cli)306307::308

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 309why, one step back
309 $ flask user create demo

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 310–312why, one step back
310
311See :ref:`testing-cli` for an overview of how to test your custom312commands.

Merge pull request #2784 from doobeh/masterDavid Lordbefore adoptionb837606

lines 313–367why, one step back
313
314315Registering Commands with Blueprints316~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~317318If your application uses blueprints, you can optionally register CLI319commands directly onto them. When your blueprint is registered onto your320application, the associated commands will be available to the ``flask``321command. By default, those commands will be nested in a group matching322the name of the blueprint.323324.. code-block:: python325326 from flask import Blueprint327328 bp = Blueprint('students', __name__)329330 @bp.cli.command('create')331 @click.argument('name')332 def create(name):333 ...334335 app.register_blueprint(bp)336337.. code-block:: text338339 $ flask students create alice340341You can alter the group name by specifying the ``cli_group`` parameter342when creating the :class:`Blueprint` object, or later with343:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.344The following are equivalent:345346.. code-block:: python347348 bp = Blueprint('students', __name__, cli_group='other')349 # or350 app.register_blueprint(bp, cli_group='other')351352.. code-block:: text353354 $ flask other create alice355356Specifying ``cli_group=None`` will remove the nesting and merge the357commands directly to the application's level:358359.. code-block:: python360361 bp = Blueprint('students', __name__, cli_group=None)362 # or363 app.register_blueprint(bp, cli_group=None)364365.. code-block:: text366367 $ flask create alice

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 368–382why, one step back
368
369370Application Context371~~~~~~~~~~~~~~~~~~~372373Commands added using the Flask app's :attr:`~Flask.cli`374:meth:`~cli.AppGroup.command` decorator will be executed with an application375context pushed, so your command and extensions have access to the app and its376configuration. If you create a command using the Click :func:`~click.command`377decorator instead of the Flask decorator, you can use378:func:`~cli.with_appcontext` to get the same behavior. ::379380 import click381 from flask.cli import with_appcontext382

Merge pull request #2915 from loomchild/masterDavid Lordbefore adoptionc92001d

line 383why, one step back
383 @click.command()

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 384–416why, one step back
384 @with_appcontext
385 def do_work():386 ...387388 app.cli.add_command(do_work)389390If you're sure a command doesn't need the context, you can disable it::391392 @app.cli.command(with_appcontext=False)393 def do_work():394 ...395396397Plugins398-------399400Flask will automatically load commands specified in the ``flask.commands``401`entry point`_. This is useful for extensions that want to add commands when402they are installed. Entry points are specified in :file:`setup.py` ::403404 from setuptools import setup405406 setup(407 name='flask-my-extension',408 ...,409 entry_points={410 'flask.commands': [411 'my-command=flask_my_extension.commands:cli'412 ],413 },414 )415416

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 417why, one step back
417.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 418–485why, one step back
418
419Inside :file:`flask_my_extension/commands.py` you can then export a Click420object::421422 import click423424 @click.command()425 def cli():426 ...427428Once that package is installed in the same virtualenv as your Flask project,429you can run ``flask my-command`` to invoke the command.430431432.. _custom-scripts:433434Custom Scripts435--------------436437When you are using the app factory pattern, it may be more convenient to define438your own Click script. Instead of using ``FLASK_APP`` and letting Flask load439your application, you can create your own Click object and export it as a440`console script`_ entry point.441442Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::443444 import click445 from flask import Flask446 from flask.cli import FlaskGroup447448 def create_app():449 app = Flask('wiki')450 # other setup451 return app452453 @click.group(cls=FlaskGroup, create_app=create_app)454 def cli():455 """Management script for the Wiki application."""456457Define the entry point in :file:`setup.py`::458459 from setuptools import setup460461 setup(462 name='flask-my-extension',463 ...,464 entry_points={465 'console_scripts': [466 'wiki=wiki:cli'467 ],468 },469 )470471Install the application in the virtualenv in editable mode and the custom472script is available. Note that you don't need to set ``FLASK_APP``. ::473474 $ pip install -e .475 $ wiki run476477.. admonition:: Errors in Custom Scripts478479 When using a custom script, if you introduce an error in your480 module-level code, the reloader will fail because it can no longer481 load the entry point.482483 The ``flask`` command, being separate from your code, does not have484 this issue and is recommended in most cases.485

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 486why, one step back
486.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 487–491why, one step back
487
488489PyCharm Integration490-------------------491

Merge branch '1.1.x'David Lordbefore adoption96b4dca

lines 492–495why, one step back
492PyCharm Professional provides a special Flask run configuration. For
493the Community Edition, we need to configure it to call the ``flask run``494CLI command with the correct environment variables. These instructions495should be similar for any other IDE you might want to use.

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 496–503why, one step back
496
497In PyCharm, with your project open, click on *Run* from the menu bar and498go to *Edit Configurations*. You'll be greeted by a screen similar to499this:500501.. image:: _static/pycharm-runconfig.png502 :align: center503 :class: screenshot

Merge branch '1.1.x'David Lordbefore adoption96b4dca

line 504why, one step back
504 :alt: Screenshot of PyCharms's run configuration settings.

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 505–511why, one step back
505
506There's quite a few options to change, but once we've done it for one507command, we can easily copy the entire configuration and make a single508tweak to give us access to other commands, including any custom ones you509may implement yourself.510511Click the + (*Add New Configuration*) button and select *Python*. Give

Merge branch '1.1.x'David Lordbefore adoption96b4dca

lines 512–514why, one step back
512the configuration a name such as "flask run". For the ``flask run``
513command, check "Single instance only" since you can't run the server514more than once at the same time.

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 515–524why, one step back
515
516Select *Module name* from the dropdown (**A**) then input ``flask``.517518The *Parameters* field (**B**) is set to the CLI command to execute519(with any arguments). In this example we use ``run``, which will run520the development server.521522You can skip this next step if you're using :ref:`dotenv`. We need to523add an environment variable (**C**) to identify our application. Click524on the browse button and add an entry with ``FLASK_APP`` on the left and

Merge branch '1.1.x'David Lordbefore adoption96b4dca

lines 525–526why, one step back
525the Python import or file on the right (``hello`` for example). Add an
526entry with ``FLASK_ENV`` and set it to ``development``.

Merge pull request #2707 from rochacbruno/lazy_loader_messageDavid Lordbefore adoptione102e5c

lines 527–541why, one step back
527
528Next we need to set the working directory (**D**) to be the folder where529our application resides.530531If you have installed your project as a package in your virtualenv, you532may untick the *PYTHONPATH* options (**E**). This will more accurately533match how you deploy the app later.534535Click *Apply* to save the configuration, or *OK* to save and close the536window. Select the configuration in the main PyCharm window and click537the play button next to it to run the server.538539Now that we have a configuration which runs ``flask run`` from within540PyCharm, we can copy that configuration and alter the *Script* argument541to run a different CLI command, e.g. ``flask shell``.