cli.rst
This file
Path
docs/cli.rst
468 lines · 14.4 KiB
Last changed by
Merge branch '1.0.x'David Lordbefore adoption2236ba9
History of this fileTake it
1.. 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.1213.. _Click: http://click.pocoo.org/141516Application 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.7071If ``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.7475Within 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 named81``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.878889Run 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.120121122Environments123------------124125.. versionadded:: 1.0126127The 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.132133If the env is set to ``development``, the ``flask`` command will enable134debug mode and ``flask run`` will enable the interactive debugger and135reloader.136137::138139 $ FLASK_ENV=development flask run140 * Serving Flask app "hello"141 * Environment: development142 * Debug mode: on143 * 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-919147148149Debug Mode150----------151152Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,153as described above. If you want to control debug mode separately, use154:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.155156157.. _dotenv:158159Environment Variables From dotenv160---------------------------------161162Rather than setting ``FLASK_APP`` each time you open a new terminal, you can163use Flask's dotenv support to set environment variables automatically.164165If `python-dotenv`_ is installed, running the ``flask`` command will set166environment variables defined in the files :file:`.env` and :file:`.flaskenv`.167This can be used to avoid having to set ``FLASK_APP`` manually every time you168open a new terminal, and to set configuration using environment variables169similar to how some deployment services work.170171Variables set on the command line are used over those set in :file:`.env`,172which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be173used for public variables, such as ``FLASK_APP``, while :file:`.env` should not174be committed to your repository so that it can set private variables.175176Directories are scanned upwards from the directory you call ``flask``177from to locate the files. The current working directory will be set to the178location of the file, with the assumption that that is the top level project179directory.180181The files are only loaded by the ``flask`` command or calling182:meth:`~Flask.run`. If you would like to load these files when running in183production, you should call :func:`~cli.load_dotenv` manually.184185.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme186187188Setting Command Options189~~~~~~~~~~~~~~~~~~~~~~~190191Click is configured to load default values for command options from192environment variables. The variables use the pattern193``FLASK_COMMAND_OPTION``. For example, to set the port for the run194command, instead of ``flask run --port 8000``:195196.. code-block:: bash197198 $ export FLASK_RUN_PORT=8000199 $ flask run200 * Running on http://127.0.0.1:8000/201202These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to203control default command options.204205206Disable dotenv207~~~~~~~~~~~~~~208209The ``flask`` command will show a message if it detects dotenv files but210python-dotenv is not installed.211212.. code-block:: bash213214 $ flask run215 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.216217You can tell Flask not to load dotenv files even when python-dotenv is218installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.219This can be useful if you want to load them manually, or if you're using220a project runner that loads them already. Keep in mind that the221environment variables must be set before the app loads or it won't222configure as expected.223224.. code-block:: bash225226 $ export FLASK_SKIP_DOTENV=1227 $ flask run228229230Environment Variables From virtualenv231-------------------------------------232233If you do not want to install dotenv support, you can still set environment234variables by adding them to the end of the virtualenv's :file:`activate`235script. Activating the virtualenv will set the variables.236237Unix Bash, :file:`venv/bin/activate`::238239 $ export FLASK_APP=hello240241Windows CMD, :file:`venv\\Scripts\\activate.bat`::242243 > set FLASK_APP=hello244245It is preferred to use dotenv support over this, since :file:`.flaskenv` can be246committed to the repository so that it works automatically wherever the project247is checked out.248249250Custom Commands251---------------252253The ``flask`` command is implemented using `Click`_. See that project's254documentation for full information about writing commands.255256This example adds the command ``create_user`` that takes the argument257``name``. ::258259 import click260 from flask import Flask261262 app = Flask(__name__)263264 @app.cli.command()265 @click.argument('name')266 def create_user(name):267 ...268269::270271 $ flask create_user admin272273This example adds the same command, but as ``user create``, a command in a274group. This is useful if you want to organize multiple related commands. ::275276 import click277 from flask import Flask278 from flask.cli import AppGroup279280 app = Flask(__name__)281 user_cli = AppGroup('user')282283 @user_cli.command('create')284 @click.argument('name')285 def create_user(name):286 ...287288 app.cli.add_command(user_cli)289290::291292 $ flask user create demo293294See :ref:`testing-cli` for an overview of how to test your custom295commands.296297298Application Context299~~~~~~~~~~~~~~~~~~~300301Commands added using the Flask app's :attr:`~Flask.cli`302:meth:`~cli.AppGroup.command` decorator will be executed with an application303context pushed, so your command and extensions have access to the app and its304configuration. If you create a command using the Click :func:`~click.command`305decorator instead of the Flask decorator, you can use306:func:`~cli.with_appcontext` to get the same behavior. ::307308 import click309 from flask.cli import with_appcontext310311 @click.command()312 @with_appcontext313 def do_work():314 ...315316 app.cli.add_command(do_work)317318If you're sure a command doesn't need the context, you can disable it::319320 @app.cli.command(with_appcontext=False)321 def do_work():322 ...323324325Plugins326-------327328Flask will automatically load commands specified in the ``flask.commands``329`entry point`_. This is useful for extensions that want to add commands when330they are installed. Entry points are specified in :file:`setup.py` ::331332 from setuptools import setup333334 setup(335 name='flask-my-extension',336 ...,337 entry_points={338 'flask.commands': [339 'my-command=flask_my_extension.commands:cli'340 ],341 },342 )343344345.. _entry point: https://packaging.python.org/tutorials/distributing-packages/#entry-points346347Inside :file:`flask_my_extension/commands.py` you can then export a Click348object::349350 import click351352 @click.command()353 def cli():354 ...355356Once that package is installed in the same virtualenv as your Flask project,357you can run ``flask my-command`` to invoke the command.358359360.. _custom-scripts:361362Custom Scripts363--------------364365When you are using the app factory pattern, it may be more convenient to define366your own Click script. Instead of using ``FLASK_APP`` and letting Flask load367your application, you can create your own Click object and export it as a368`console script`_ entry point.369370Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::371372 import click373 from flask import Flask374 from flask.cli import FlaskGroup375376 def create_app():377 app = Flask('wiki')378 # other setup379 return app380381 @click.group(cls=FlaskGroup, create_app=create_app)382 def cli():383 """Management script for the Wiki application."""384385Define the entry point in :file:`setup.py`::386387 from setuptools import setup388389 setup(390 name='flask-my-extension',391 ...,392 entry_points={393 'console_scripts': [394 'wiki=wiki:cli'395 ],396 },397 )398399Install the application in the virtualenv in editable mode and the custom400script is available. Note that you don't need to set ``FLASK_APP``. ::401402 $ pip install -e .403 $ wiki run404405.. admonition:: Errors in Custom Scripts406407 When using a custom script, if you introduce an error in your408 module-level code, the reloader will fail because it can no longer409 load the entry point.410411 The ``flask`` command, being separate from your code, does not have412 this issue and is recommended in most cases.413414.. _console script: https://packaging.python.org/tutorials/distributing-packages/#console-scripts415416417PyCharm Integration418-------------------419420Prior to PyCharm 2018.1, the Flask CLI features weren't yet fully421integrated into PyCharm. We have to do a few tweaks to get them working422smoothly. These instructions should be similar for any other IDE you423might want to use.424425In PyCharm, with your project open, click on *Run* from the menu bar and426go to *Edit Configurations*. You'll be greeted by a screen similar to427this:428429.. image:: _static/pycharm-runconfig.png430 :align: center431 :class: screenshot432 :alt: screenshot of pycharm's run configuration settings433434There's quite a few options to change, but once we've done it for one435command, we can easily copy the entire configuration and make a single436tweak to give us access to other commands, including any custom ones you437may implement yourself.438439Click the + (*Add New Configuration*) button and select *Python*. Give440the configuration a good descriptive name such as "Run Flask Server".441For the ``flask run`` command, check "Single instance only" since you442can't run the server more than once at the same time.443444Select *Module name* from the dropdown (**A**) then input ``flask``.445446The *Parameters* field (**B**) is set to the CLI command to execute447(with any arguments). In this example we use ``run``, which will run448the development server.449450You can skip this next step if you're using :ref:`dotenv`. We need to451add an environment variable (**C**) to identify our application. Click452on the browse button and add an entry with ``FLASK_APP`` on the left and453the Python import or file on the right (``hello`` for example).454455Next we need to set the working directory (**D**) to be the folder where456our application resides.457458If you have installed your project as a package in your virtualenv, you459may untick the *PYTHONPATH* options (**E**). This will more accurately460match how you deploy the app later.461462Click *Apply* to save the configuration, or *OK* to save and close the463window. Select the configuration in the main PyCharm window and click464the play button next to it to run the server.465466Now that we have a configuration which runs ``flask run`` from within467PyCharm, we can copy that configuration and alter the *Script* argument468to run a different CLI command, e.g. ``flask shell``.