cli.rst
This file
Path
docs/cli.rst
383 lines · 12.0 KiB
Last changed by
Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f
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.118119120Debug Mode121----------122123Set the :envvar:`FLASK_DEBUG` environment variable to override the124application's :attr:`~Flask.debug` flag. The value ``1`` enables it, ``0``125disables it. Forcing the debug flag on also enables the debugger and reloader126when running the development server. ::127128 $ FLASK_DEBUG=1 flask run129 * Serving Flask app "hello"130 * Forcing debug mode on131 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)132 * Restarting with inotify reloader133 * Debugger is active!134 * Debugger PIN: 223-456-919135136137.. _dotenv:138139Environment Variables From dotenv140---------------------------------141142Rather than setting ``FLASK_APP`` each time you open a new terminal, you can143use Flask's dotenv support to set environment variables automatically.144145If `python-dotenv`_ is installed, running the ``flask`` command will set146environment variables defined in the files :file:`.env` and :file:`.flaskenv`.147This can be used to avoid having to set ``FLASK_APP`` manually every time you148open a new terminal, and to set configuration using environment variables149similar to how some deployment services work.150151Variables set on the command line are used over those set in :file:`.env`,152which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be153used for public variables, such as ``FLASK_APP``, while :file:`.env` should not154be committed to your repository so that it can set private variables.155156Directories are scanned upwards from the directory you call ``flask``157from to locate the files. The current working directory will be set to the158location of the file, with the assumption that that is the top level project159directory.160161The files are only loaded by the ``flask`` command or calling162:meth:`~Flask.run`. If you would like to load these files when running in163production, you should call :func:`~cli.load_dotenv` manually.164165.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme166167168Environment Variables From virtualenv169-------------------------------------170171If you do not want to install dotenv support, you can still set environment172variables by adding them to the end of the virtualenv's :file:`activate`173script. Activating the virtualenv will set the variables.174175Unix Bash, :file:`venv/bin/activate`::176177 export FLASK_APP=hello178179Windows CMD, :file:`venv\Scripts\activate.bat`::180181 set FLASK_APP=hello182183It is preferred to use dotenv support over this, since :file:`.flaskenv` can be184committed to the repository so that it works automatically wherever the project185is checked out.186187188Custom Commands189---------------190191The ``flask`` command is implemented using `Click`_. See that project's192documentation for full information about writing commands.193194This example adds the command ``create_user`` that takes the argument195``name``. ::196197 import click198 from flask import Flask199200 app = Flask(__name__)201202 @app.cli.command()203 @click.argument('name')204 def create_user(name):205 ...206207::208209 flask create_user admin210211This example adds the same command, but as ``user create``, a command in a212group. This is useful if you want to organize multiple related commands. ::213214 import click215 from flask import Flask216 from flask.cli import AppGroup217218 app = Flask(__name__)219 user_cli = AppGroup('user')220221 @user_cli.command('create')222 @click.argument('name')223 def create_user(name):224 ...225226 app.cli.add_command(user_cli)227228::229230 flask user create demo231232233Application Context234~~~~~~~~~~~~~~~~~~~235236Commands added using the Flask app's :attr:`~Flask.cli`237:meth:`~cli.AppGroup.command` decorator will be executed with an application238context pushed, so your command and extensions have access to the app and its239configuration. If you create a command using the Click :func:`~click.command`240decorator instead of the Flask decorator, you can use241:func:`~cli.with_appcontext` to get the same behavior. ::242243 import click244 from flask.cli import with_appcontext245246 @click.command247 @with_appcontext248 def do_work():249 ...250251 app.cli.add_command(do_work)252253If you're sure a command doesn't need the context, you can disable it::254255 @app.cli.command(with_appcontext=False)256 def do_work():257 ...258259260Plugins261-------262263Flask will automatically load commands specified in the ``flask.commands``264`entry point`_. This is useful for extensions that want to add commands when265they are installed. Entry points are specified in :file:`setup.py` ::266267 from setuptools import setup268269 setup(270 name='flask-my-extension',271 ...,272 entry_points={273 'flask.commands': [274 'my-command=flask_my_extension.commands:cli'275 ],276 },277 )278279280.. _entry point: https://packaging.python.org/tutorials/distributing-packages/#entry-points281282Inside :file:`flask_my_extension/commands.py` you can then export a Click283object::284285 import click286287 @click.command()288 def cli():289 ...290291Once that package is installed in the same virtualenv as your Flask project,292you can run ``flask my-command`` to invoke the command.293294295.. _custom-scripts:296297Custom Scripts298--------------299300When you are using the app factory pattern, it may be more convenient to define301your own Click script. Instead of using ``FLASK_APP`` and letting Flask load302your application, you can create your own Click object and export it as a303`console script`_ entry point.304305Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::306307 import click308 from flask import Flask309 from flask.cli import FlaskGroup310311 def create_app():312 app = Flask('wiki')313 # other setup314 return app315316 @click.group(cls=FlaskGroup, create_app=create_app)317 def cli():318 """Management script for the Wiki application."""319320Define the entry point in :file:`setup.py`::321322 from setuptools import setup323324 setup(325 name='flask-my-extension',326 ...,327 entry_points={328 'console_scripts': [329 'wiki=wiki:cli'330 ],331 },332 )333334Install the application in the virtualenv in editable mode and the custom335script is available. Note that you don't need to set ``FLASK_APP``. ::336337 $ pip install -e .338 $ wiki run339340.. _console script: https://packaging.python.org/tutorials/distributing-packages/#console-scripts341342343PyCharm Integration344-------------------345346The new Flask CLI features aren't yet fully integrated into the PyCharm IDE,347so we have to do a few tweaks to get them working smoothly. These instructions348should be similar for any other IDE you might want to use.349350In PyCharm, with your project open, click on *Run* from the menu bar and go to351*Edit Configurations*. You'll be greeted by a screen similar to this:352353.. image:: _static/pycharm-runconfig.png354 :align: center355 :class: screenshot356 :alt: screenshot of pycharm's run configuration settings357358There's quite a few options to change, but once we've done it for one command,359we can easily copy the entire configuration and make a single tweak to give us360access to other commands, including any custom ones you may implement yourself.361362For the *Script* input (**A**), navigate to your project's virtual environment.363Within that folder, pick the ``flask`` executable which will reside in the364``bin`` folder, or in the ``Scripts`` on Windows.365366The *Script Parameter* field (**B**) is set to the CLI command you to execute.367In this example we use ``run``, which will run the development server.368369You can skip this next step if you're using :ref:`dotenv`. We need to add an370environment variable (**C**) to identify our application. Click on the browse371button and add an entry with ``FLASK_APP`` on the left and the name of the372Python file or package on the right (``app.py`` for example).373374Next we need to set the working directory (**D**) to be the same folder where375our application file or package resides. PyCharm changed it to the directory376with the ``flask`` executable when we selected it earlier, which is incorrect.377378Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a379good descriptive name, such as "Run Flask Server", and click *Apply*.380381Now that we have a configuration which runs ``flask run`` from within PyCharm,382we can simply copy that configuration and alter the *Script* argument383to run a different CLI command, e.g. ``flask shell``.