cli.rst
This file
Path
docs/cli.rst
542 lines · 16.4 KiB
Last changed by
Merge branch '1.0.x'David Lordbefore adoption1351d0a
History of this fileTake it
The walk stopped after 200 commits: lines older than 40745bb point at it.
Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 1–12why, one step back1.. currentmodule:: flask23.. _cli:45Command Line Interface6======================78Installing Flask installs the ``flask`` script, a `Click`_ command line9interface, in your virtualenv. Executed from the terminal, this script gives10access to built-in, extension, and application-defined commands. The ``--help``11option will give more information about any commands and options.12Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 13why, one step back13.. _Click: https://click.palletsprojects.com/Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 14–70why, one step back141516Application Discovery17---------------------1819The ``flask`` command is installed by Flask, not your application; it must be20told where to find your application in order to use it. The ``FLASK_APP``21environment variable is used to specify how to load the application.2223Unix Bash (Linux, Mac, etc.)::2425 $ export FLASK_APP=hello26 $ flask run2728Windows CMD::2930 > set FLASK_APP=hello31 > flask run3233Windows PowerShell::3435 > $env:FLASK_APP = "hello"36 > flask run3738While ``FLASK_APP`` supports a variety of options for specifying your39application, most use cases should be simple. Here are the typical values:4041(nothing)42 The file :file:`wsgi.py` is imported, automatically detecting an app43 (``app``). This provides an easy way to create an app from a factory with44 extra arguments.4546``FLASK_APP=hello``47 The name is imported, automatically detecting an app (``app``) or factory48 (``create_app``).4950----5152``FLASK_APP`` has three parts: an optional path that sets the current working53directory, a Python file or dotted import path, and an optional variable54name of the instance or factory. If the name is a factory, it can optionally55be followed by arguments in parentheses. The following values demonstrate these56parts:5758``FLASK_APP=src/hello``59 Sets the current working directory to ``src`` then imports ``hello``.6061``FLASK_APP=hello.web``62 Imports the path ``hello.web``.6364``FLASK_APP=hello:app2``65 Uses the ``app2`` Flask instance in ``hello``.6667``FLASK_APP="hello:create_app('dev')"``68 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``69 as the argument.70Merge branch '1.0.x'David Lordbefore adoption2236ba9
lines 71–73why, one step back71If ``FLASK_APP`` is not set, the command will try to import "app" or72"wsgi" (as a ".py" file, or package) and try to detect an application73instance or factory.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 74–80why, one step back7475Within the given import, the command looks for an application instance named76``app`` or ``application``, then any application instance. If no instance is77found, the command looks for a factory function named ``create_app`` or78``make_app`` that returns an instance.7980When calling an application factory, if the factory takes an argument namedMerge pull request #2870 from jerr0328/docs-update-cli-scriptinfoDavid Lordbefore adoption93e4b71
lines 81–86why, one step back81``script_info``, then the :class:`~cli.ScriptInfo` instance is passed as a82keyword argument. If the application factory takes only one argument and no83parentheses follow the factory name, the :class:`~cli.ScriptInfo` instance84is passed as a positional argument. If parentheses follow the factory name,85their contents are parsed as Python literals and passes as arguments to the86function. This means that strings must still be in quotes.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 87–120why, one step back878889Run the Development Server90--------------------------9192The :func:`run <cli.run_command>` command will start the development server. It93replaces the :meth:`Flask.run` method in most cases. ::9495 $ flask run96 * Serving Flask app "hello"97 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)9899.. warning:: Do not use this command to run your application in production.100 Only use the development server during development. The development server101 is provided for convenience, but is not designed to be particularly secure,102 stable, or efficient. See :ref:`deployment` for how to run in production.103104105Open a Shell106------------107108To explore the data in your application, you can start an interactive Python109shell with the :func:`shell <cli.shell_command>` command. An application110context will be active, and the app instance will be imported. ::111112 $ flask shell113 Python 3.6.2 (default, Jul 20 2017, 03:52:27)114 [GCC 7.1.1 20170630] on linux115 App: example116 Instance: /home/user/Projects/hello/instance117 >>>118119Use :meth:`~Flask.shell_context_processor` to add other automatic imports.120Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978
line 121why, one step back121Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522
lines 122–123why, one step back122Environments123------------Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
line 124why, one step back124Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522
lines 125–126why, one step back125.. versionadded:: 1.0126Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978
lines 127–131why, one step back127The environment in which the Flask app runs is set by the128:envvar:`FLASK_ENV` environment variable. If not set it defaults to129``production``. The other recognized environment is ``development``.130Flask and extensions may choose to enable behaviors based on the131environment.Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522
line 132why, one step back132Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978
lines 133–135why, one step back133If the env is set to ``development``, the ``flask`` command will enable134debug mode and ``flask run`` will enable the interactive debugger and135reloader.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
line 136why, one step back136Add Support for FLASK_ENV (#2570)Armin Ronacherbefore adoption2433522
lines 137–138why, one step back137::138Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978
line 139why, one step back139 $ FLASK_ENV=development flask runMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
line 140why, one step back140 * Serving Flask app "hello"Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978
lines 141–142why, one step back141 * Environment: development142 * Debug mode: onMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 143–146why, one step back143 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)144 * Restarting with inotify reloader145 * Debugger is active!146 * Debugger PIN: 223-456-919Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978
lines 147–148why, one step back147148Merge pull request #2898 from rochacbruno/2897-Add-Extra-Files-to-CLIDavid Lordbefore adoption2616d97
lines 149–167why, one step back149Watch Extra Files with the Reloader150~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~151152When using development mode, the reloader will trigger whenever your153Python code or imported modules change. The reloader can watch154additional files with the ``--extra-files`` option, or the155``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are156separated with ``:``, or ``;`` on Windows.157158.. code-block:: none159160 $ flask run --extra-files file1:dirA/file2:dirB/161 # or162 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/163 $ flask run164 * Running on http://127.0.0.1:8000/165 * Detected change in '/path/to/file1', reloading166167Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978
lines 168–173why, one step back168Debug Mode169----------170171Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,172as described above. If you want to control debug mode separately, use173:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 174–206why, one step back174175176.. _dotenv:177178Environment Variables From dotenv179---------------------------------180181Rather than setting ``FLASK_APP`` each time you open a new terminal, you can182use Flask's dotenv support to set environment variables automatically.183184If `python-dotenv`_ is installed, running the ``flask`` command will set185environment variables defined in the files :file:`.env` and :file:`.flaskenv`.186This can be used to avoid having to set ``FLASK_APP`` manually every time you187open a new terminal, and to set configuration using environment variables188similar to how some deployment services work.189190Variables set on the command line are used over those set in :file:`.env`,191which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be192used for public variables, such as ``FLASK_APP``, while :file:`.env` should not193be committed to your repository so that it can set private variables.194195Directories are scanned upwards from the directory you call ``flask``196from to locate the files. The current working directory will be set to the197location of the file, with the assumption that that is the top level project198directory.199200The files are only loaded by the ``flask`` command or calling201:meth:`~Flask.run`. If you would like to load these files when running in202production, you should call :func:`~cli.load_dotenv` manually.203204.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme205206document cli option env varsDavid Lordbefore adoption93698b5
lines 207–214why, one step back207Setting Command Options208~~~~~~~~~~~~~~~~~~~~~~~209210Click is configured to load default values for command options from211environment variables. The variables use the pattern212``FLASK_COMMAND_OPTION``. For example, to set the port for the run213command, instead of ``flask run --port 8000``:214Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
line 215why, one step back215.. code-block:: bashdocument cli option env varsDavid Lordbefore adoption93698b5
line 216why, one step back216Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
lines 217–218why, one step back217 $ export FLASK_RUN_PORT=8000218 $ flask rundocument cli option env varsDavid Lordbefore adoption93698b5
lines 219–224why, one step back219 * Running on http://127.0.0.1:8000/220221These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to222control default command options.223224Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185
lines 225–230why, one step back225Disable dotenv226~~~~~~~~~~~~~~227228The ``flask`` command will show a message if it detects dotenv files but229python-dotenv is not installed.230Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
line 231why, one step back231.. code-block:: bashMerge branch '1.0-maintenance'David Lordbefore adoption1fa9185
line 232why, one step back232Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 233why, one step back233 $ flask runMerge branch '1.0-maintenance'David Lordbefore adoption1fa9185
lines 234–242why, one step back234 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.235236You can tell Flask not to load dotenv files even when python-dotenv is237installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.238This can be useful if you want to load them manually, or if you're using239a project runner that loads them already. Keep in mind that the240environment variables must be set before the app loads or it won't241configure as expected.242Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
line 243why, one step back243.. code-block:: bashMerge branch '1.0-maintenance'David Lordbefore adoption1fa9185
line 244why, one step back244Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
lines 245–246why, one step back245 $ export FLASK_SKIP_DOTENV=1246 $ flask runMerge branch '1.0-maintenance'David Lordbefore adoption1fa9185
lines 247–248why, one step back247248Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 249–257why, one step back249Environment Variables From virtualenv250-------------------------------------251252If you do not want to install dotenv support, you can still set environment253variables by adding them to the end of the virtualenv's :file:`activate`254script. Activating the virtualenv will set the variables.255256Unix Bash, :file:`venv/bin/activate`::257Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 258why, one step back258 $ export FLASK_APP=helloMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 259–261why, one step back259260Windows CMD, :file:`venv\\Scripts\\activate.bat`::261Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 262why, one step back262 > set FLASK_APP=helloMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 263–274why, one step back263264It is preferred to use dotenv support over this, since :file:`.flaskenv` can be265committed to the repository so that it works automatically wherever the project266is checked out.267268269Custom Commands270---------------271272The ``flask`` command is implemented using `Click`_. See that project's273documentation for full information about writing commands.274Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 275why, one step back275This example adds the command ``create-user`` that takes the argumentMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 276–282why, one step back276``name``. ::277278 import click279 from flask import Flask280281 app = Flask(__name__)282Merge branch '1.0.x'David Lordbefore adoption1351d0a
lines 283–284why, one step back283 @app.cli.command("create-user")284 @click.argument("name")Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 285–289why, one step back285 def create_user(name):286 ...287288::289Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 290why, one step back290 $ flask create-user adminMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 291–310why, one step back291292This example adds the same command, but as ``user create``, a command in a293group. This is useful if you want to organize multiple related commands. ::294295 import click296 from flask import Flask297 from flask.cli import AppGroup298299 app = Flask(__name__)300 user_cli = AppGroup('user')301302 @user_cli.command('create')303 @click.argument('name')304 def create_user(name):305 ...306307 app.cli.add_command(user_cli)308309::310Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 311why, one step back311 $ flask user create demoMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
line 312why, one step back312Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 313–314why, one step back313See :ref:`testing-cli` for an overview of how to test your custom314commands.Merge pull request #2784 from doobeh/masterDavid Lordbefore adoptionb837606
lines 315–369why, one step back315316317Registering Commands with Blueprints318~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~319320If your application uses blueprints, you can optionally register CLI321commands directly onto them. When your blueprint is registered onto your322application, the associated commands will be available to the ``flask``323command. By default, those commands will be nested in a group matching324the name of the blueprint.325326.. code-block:: python327328 from flask import Blueprint329330 bp = Blueprint('students', __name__)331332 @bp.cli.command('create')333 @click.argument('name')334 def create(name):335 ...336337 app.register_blueprint(bp)338339.. code-block:: text340341 $ flask students create alice342343You can alter the group name by specifying the ``cli_group`` parameter344when creating the :class:`Blueprint` object, or later with345:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.346The following are equivalent:347348.. code-block:: python349350 bp = Blueprint('students', __name__, cli_group='other')351 # or352 app.register_blueprint(bp, cli_group='other')353354.. code-block:: text355356 $ flask other create alice357358Specifying ``cli_group=None`` will remove the nesting and merge the359commands directly to the application's level:360361.. code-block:: python362363 bp = Blueprint('students', __name__, cli_group=None)364 # or365 app.register_blueprint(bp, cli_group=None)366367.. code-block:: text368369 $ flask create aliceMerge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
line 370why, one step back370Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 371–384why, one step back371372Application Context373~~~~~~~~~~~~~~~~~~~374375Commands added using the Flask app's :attr:`~Flask.cli`376:meth:`~cli.AppGroup.command` decorator will be executed with an application377context pushed, so your command and extensions have access to the app and its378configuration. If you create a command using the Click :func:`~click.command`379decorator instead of the Flask decorator, you can use380:func:`~cli.with_appcontext` to get the same behavior. ::381382 import click383 from flask.cli import with_appcontext384Merge pull request #2915 from loomchild/masterDavid Lordbefore adoptionc92001d
line 385why, one step back385 @click.command()Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 386–418why, one step back386 @with_appcontext387 def do_work():388 ...389390 app.cli.add_command(do_work)391392If you're sure a command doesn't need the context, you can disable it::393394 @app.cli.command(with_appcontext=False)395 def do_work():396 ...397398399Plugins400-------401402Flask will automatically load commands specified in the ``flask.commands``403`entry point`_. This is useful for extensions that want to add commands when404they are installed. Entry points are specified in :file:`setup.py` ::405406 from setuptools import setup407408 setup(409 name='flask-my-extension',410 ...,411 entry_points={412 'flask.commands': [413 'my-command=flask_my_extension.commands:cli'414 ],415 },416 )417418Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 419why, one step back419.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-pointsMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 420–478why, one step back420421Inside :file:`flask_my_extension/commands.py` you can then export a Click422object::423424 import click425426 @click.command()427 def cli():428 ...429430Once that package is installed in the same virtualenv as your Flask project,431you can run ``flask my-command`` to invoke the command.432433434.. _custom-scripts:435436Custom Scripts437--------------438439When you are using the app factory pattern, it may be more convenient to define440your own Click script. Instead of using ``FLASK_APP`` and letting Flask load441your application, you can create your own Click object and export it as a442`console script`_ entry point.443444Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::445446 import click447 from flask import Flask448 from flask.cli import FlaskGroup449450 def create_app():451 app = Flask('wiki')452 # other setup453 return app454455 @click.group(cls=FlaskGroup, create_app=create_app)456 def cli():457 """Management script for the Wiki application."""458459Define the entry point in :file:`setup.py`::460461 from setuptools import setup462463 setup(464 name='flask-my-extension',465 ...,466 entry_points={467 'console_scripts': [468 'wiki=wiki:cli'469 ],470 },471 )472473Install the application in the virtualenv in editable mode and the custom474script is available. Note that you don't need to set ``FLASK_APP``. ::475476 $ pip install -e .477 $ wiki run478Merge pull request #2610 from pallets/cli-syntaxerrorDavid Lordbefore adoption94aaa24
lines 479–487why, one step back479.. admonition:: Errors in Custom Scripts480481 When using a custom script, if you introduce an error in your482 module-level code, the reloader will fail because it can no longer483 load the entry point.484485 The ``flask`` command, being separate from your code, does not have486 this issue and is recommended in most cases.487Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 488why, one step back488.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scriptsMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 489–493why, one step back489490491PyCharm Integration492-------------------493Merge pull request #2610 from pallets/cli-syntaxerrorDavid Lordbefore adoption94aaa24
lines 494–497why, one step back494Prior to PyCharm 2018.1, the Flask CLI features weren't yet fully495integrated into PyCharm. We have to do a few tweaks to get them working496smoothly. These instructions should be similar for any other IDE you497might want to use.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 498–542why, one step back498499In PyCharm, with your project open, click on *Run* from the menu bar and500go to *Edit Configurations*. You'll be greeted by a screen similar to501this:502503.. image:: _static/pycharm-runconfig.png504 :align: center505 :class: screenshot506 :alt: screenshot of pycharm's run configuration settings507508There's quite a few options to change, but once we've done it for one509command, we can easily copy the entire configuration and make a single510tweak to give us access to other commands, including any custom ones you511may implement yourself.512513Click the + (*Add New Configuration*) button and select *Python*. Give514the configuration a good descriptive name such as "Run Flask Server".515For the ``flask run`` command, check "Single instance only" since you516can't run the server more than once at the same time.517518Select *Module name* from the dropdown (**A**) then input ``flask``.519520The *Parameters* field (**B**) is set to the CLI command to execute521(with any arguments). In this example we use ``run``, which will run522the development server.523524You can skip this next step if you're using :ref:`dotenv`. We need to525add an environment variable (**C**) to identify our application. Click526on the browse button and add an entry with ``FLASK_APP`` on the left and527the Python import or file on the right (``hello`` for example).528529Next we need to set the working directory (**D**) to be the folder where530our application resides.531532If you have installed your project as a package in your virtualenv, you533may untick the *PYTHONPATH* options (**E**). This will more accurately534match how you deploy the app later.535536Click *Apply* to save the configuration, or *OK* to save and close the537window. Select the configuration in the main PyCharm window and click538the play button next to it to run the server.539540Now that we have a configuration which runs ``flask run`` from within541PyCharm, we can copy that configuration and alter the *Script* argument542to run a different CLI command, e.g. ``flask shell``.