cli.rst
This file
Path
docs/cli.rst
424 lines · 13.0 KiB
Last changed by
document testing cli commandsDavid Lordbefore adoptionae30fe7
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 look for a file called72:file:`wsgi.py` or :file:`app.py` and try to detect an application instance or73factory.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``info``, then the :class:`~cli.ScriptInfo` instance is passed as a keyword82argument. If parentheses follow the factory name, their contents are parsed83as Python literals and passes as arguments to the function. This means that84strings must still be in quotes.858687Run 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,100 stable, or efficient. See :ref:`deployment` for how to run in production.101102103Open 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-919145146147Debug Mode148----------149150Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,151as described above. If you want to control debug mode separately, use152:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.153154155.. _dotenv:156157Environment Variables From dotenv158---------------------------------159160Rather than setting ``FLASK_APP`` each time you open a new terminal, you can161use Flask's dotenv support to set environment variables automatically.162163If `python-dotenv`_ is installed, running the ``flask`` command will set164environment variables defined in the files :file:`.env` and :file:`.flaskenv`.165This can be used to avoid having to set ``FLASK_APP`` manually every time you166open a new terminal, and to set configuration using environment variables167similar to how some deployment services work.168169Variables set on the command line are used over those set in :file:`.env`,170which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be171used for public variables, such as ``FLASK_APP``, while :file:`.env` should not172be committed to your repository so that it can set private variables.173174Directories are scanned upwards from the directory you call ``flask``175from to locate the files. The current working directory will be set to the176location of the file, with the assumption that that is the top level project177directory.178179The files are only loaded by the ``flask`` command or calling180:meth:`~Flask.run`. If you would like to load these files when running in181production, you should call :func:`~cli.load_dotenv` manually.182183.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme184185186Environment Variables From virtualenv187-------------------------------------188189If you do not want to install dotenv support, you can still set environment190variables by adding them to the end of the virtualenv's :file:`activate`191script. Activating the virtualenv will set the variables.192193Unix Bash, :file:`venv/bin/activate`::194195 export FLASK_APP=hello196197Windows CMD, :file:`venv\\Scripts\\activate.bat`::198199 set FLASK_APP=hello200201It is preferred to use dotenv support over this, since :file:`.flaskenv` can be202committed to the repository so that it works automatically wherever the project203is checked out.204205206Custom Commands207---------------208209The ``flask`` command is implemented using `Click`_. See that project's210documentation for full information about writing commands.211212This example adds the command ``create_user`` that takes the argument213``name``. ::214215 import click216 from flask import Flask217218 app = Flask(__name__)219220 @app.cli.command()221 @click.argument('name')222 def create_user(name):223 ...224225::226227 flask create_user admin228229This example adds the same command, but as ``user create``, a command in a230group. This is useful if you want to organize multiple related commands. ::231232 import click233 from flask import Flask234 from flask.cli import AppGroup235236 app = Flask(__name__)237 user_cli = AppGroup('user')238239 @user_cli.command('create')240 @click.argument('name')241 def create_user(name):242 ...243244 app.cli.add_command(user_cli)245246::247248 flask user create demo249250See :ref:`testing-cli` for an overview of how to test your custom251commands.252253254Application Context255~~~~~~~~~~~~~~~~~~~256257Commands added using the Flask app's :attr:`~Flask.cli`258:meth:`~cli.AppGroup.command` decorator will be executed with an application259context pushed, so your command and extensions have access to the app and its260configuration. If you create a command using the Click :func:`~click.command`261decorator instead of the Flask decorator, you can use262:func:`~cli.with_appcontext` to get the same behavior. ::263264 import click265 from flask.cli import with_appcontext266267 @click.command268 @with_appcontext269 def do_work():270 ...271272 app.cli.add_command(do_work)273274If you're sure a command doesn't need the context, you can disable it::275276 @app.cli.command(with_appcontext=False)277 def do_work():278 ...279280281Plugins282-------283284Flask will automatically load commands specified in the ``flask.commands``285`entry point`_. This is useful for extensions that want to add commands when286they are installed. Entry points are specified in :file:`setup.py` ::287288 from setuptools import setup289290 setup(291 name='flask-my-extension',292 ...,293 entry_points={294 'flask.commands': [295 'my-command=flask_my_extension.commands:cli'296 ],297 },298 )299300301.. _entry point: https://packaging.python.org/tutorials/distributing-packages/#entry-points302303Inside :file:`flask_my_extension/commands.py` you can then export a Click304object::305306 import click307308 @click.command()309 def cli():310 ...311312Once that package is installed in the same virtualenv as your Flask project,313you can run ``flask my-command`` to invoke the command.314315316.. _custom-scripts:317318Custom Scripts319--------------320321When you are using the app factory pattern, it may be more convenient to define322your own Click script. Instead of using ``FLASK_APP`` and letting Flask load323your application, you can create your own Click object and export it as a324`console script`_ entry point.325326Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::327328 import click329 from flask import Flask330 from flask.cli import FlaskGroup331332 def create_app():333 app = Flask('wiki')334 # other setup335 return app336337 @click.group(cls=FlaskGroup, create_app=create_app)338 def cli():339 """Management script for the Wiki application."""340341Define the entry point in :file:`setup.py`::342343 from setuptools import setup344345 setup(346 name='flask-my-extension',347 ...,348 entry_points={349 'console_scripts': [350 'wiki=wiki:cli'351 ],352 },353 )354355Install the application in the virtualenv in editable mode and the custom356script is available. Note that you don't need to set ``FLASK_APP``. ::357358 $ pip install -e .359 $ wiki run360361.. admonition:: Errors in Custom Scripts362363 When using a custom script, if you introduce an error in your364 module-level code, the reloader will fail because it can no longer365 load the entry point.366367 The ``flask`` command, being separate from your code, does not have368 this issue and is recommended in most cases.369370.. _console script: https://packaging.python.org/tutorials/distributing-packages/#console-scripts371372373PyCharm Integration374-------------------375376Prior to PyCharm 2018.1, the Flask CLI features weren't yet fully377integrated into PyCharm. We have to do a few tweaks to get them working378smoothly. These instructions should be similar for any other IDE you379might want to use.380381In PyCharm, with your project open, click on *Run* from the menu bar and382go to *Edit Configurations*. You'll be greeted by a screen similar to383this:384385.. image:: _static/pycharm-runconfig.png386 :align: center387 :class: screenshot388 :alt: screenshot of pycharm's run configuration settings389390There's quite a few options to change, but once we've done it for one391command, we can easily copy the entire configuration and make a single392tweak to give us access to other commands, including any custom ones you393may implement yourself.394395Click the + (*Add New Configuration*) button and select *Python*. Give396the configuration a good descriptive name such as "Run Flask Server".397For the ``flask run`` command, check "Single instance only" since you398can't run the server more than once at the same time.399400Select *Module name* from the dropdown (**A**) then input ``flask``.401402The *Parameters* field (**B**) is set to the CLI command to execute403(with any arguments). In this example we use ``run``, which will run404the development server.405406You can skip this next step if you're using :ref:`dotenv`. We need to407add an environment variable (**C**) to identify our application. Click408on the browse button and add an entry with ``FLASK_APP`` on the left and409the Python import or file on the right (``hello`` for example).410411Next we need to set the working directory (**D**) to be the folder where412our application resides.413414If you have installed your project as a package in your virtualenv, you415may untick the *PYTHONPATH* options (**E**). This will more accurately416match how you deploy the app later.417418Click *Apply* to save the configuration, or *OK* to save and close the419window. Select the configuration in the main PyCharm window and click420the play button next to it to run the server.421422Now that we have a configuration which runs ``flask run`` from within423PyCharm, we can copy that configuration and alter the *Script* argument424to run a different CLI command, e.g. ``flask shell``.