cli.rst
This file
Path
docs/cli.rst
658 lines · 19.0 KiB
Last changed by
Merge branch '2.0.x'David Lordbefore adoptionedac7e3
History of this fileTake it
1.. currentmodule:: flask23Command 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.1011.. _Click: https://click.palletsprojects.com/121314Application 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.2021.. tabs::2223 .. group-tab:: Bash2425 .. code-block:: text2627 $ export FLASK_APP=hello28 $ flask run2930 .. group-tab:: CMD3132 .. code-block:: text3334 > set FLASK_APP=hello35 > flask run3637 .. group-tab:: Powershell3839 .. code-block:: text4041 > $env:FLASK_APP = "hello"42 > flask run4344While ``FLASK_APP`` supports a variety of options for specifying your45application, most use cases should be simple. Here are the typical values:4647(nothing)48 The name "app" or "wsgi" is imported (as a ".py" file, or package),49 automatically detecting an app (``app`` or ``application``) or50 factory (``create_app`` or ``make_app``).5152``FLASK_APP=hello``53 The given name is imported, automatically detecting an app (``app``54 or ``application``) or factory (``create_app`` or ``make_app``).5556----5758``FLASK_APP`` has three parts: an optional path that sets the current working59directory, a Python file or dotted import path, and an optional variable60name of the instance or factory. If the name is a factory, it can optionally61be followed by arguments in parentheses. The following values demonstrate these62parts:6364``FLASK_APP=src/hello``65 Sets the current working directory to ``src`` then imports ``hello``.6667``FLASK_APP=hello.web``68 Imports the path ``hello.web``.6970``FLASK_APP=hello:app2``71 Uses the ``app2`` Flask instance in ``hello``.7273``FLASK_APP="hello:create_app('dev')"``74 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``75 as the argument.7677If ``FLASK_APP`` is not set, the command will try to import "app" or78"wsgi" (as a ".py" file, or package) and try to detect an application79instance or factory.8081Within the given import, the command looks for an application instance named82``app`` or ``application``, then any application instance. If no instance is83found, the command looks for a factory function named ``create_app`` or84``make_app`` that returns an instance.8586If parentheses follow the factory name, their contents are parsed as87Python literals and passed as arguments and keyword arguments to the88function. This means that strings must still be in quotes.899091Run the Development Server92--------------------------9394The :func:`run <cli.run_command>` command will start the development server. It95replaces the :meth:`Flask.run` method in most cases. ::9697 $ flask run98 * Serving Flask app "hello"99 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)100101.. warning:: Do not use this command to run your application in production.102 Only use the development server during development. The development server103 is provided for convenience, but is not designed to be particularly secure,104 stable, or efficient. See :doc:`/deploying/index` for how to run in production.105106If another program is already using port 5000, you'll see107``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the108server tries to start. See :ref:`address-already-in-use` for how to109handle that.110111112Open a Shell113------------114115To explore the data in your application, you can start an interactive Python116shell with the :func:`shell <cli.shell_command>` command. An application117context will be active, and the app instance will be imported. ::118119 $ flask shell120 Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux121 App: example [production]122 Instance: /home/david/Projects/pallets/flask/instance123 >>>124125Use :meth:`~Flask.shell_context_processor` to add other automatic imports.126127128Environments129------------130131.. versionadded:: 1.0132133The environment in which the Flask app runs is set by the134:envvar:`FLASK_ENV` environment variable. If not set it defaults to135``production``. The other recognized environment is ``development``.136Flask and extensions may choose to enable behaviors based on the137environment.138139If the env is set to ``development``, the ``flask`` command will enable140debug mode and ``flask run`` will enable the interactive debugger and141reloader.142143.. tabs::144145 .. group-tab:: Bash146147 .. code-block:: text148149 $ export FLASK_ENV=development150 $ flask run151 * Serving Flask app "hello"152 * Environment: development153 * Debug mode: on154 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)155 * Restarting with inotify reloader156 * Debugger is active!157 * Debugger PIN: 223-456-919158159 .. group-tab:: CMD160161 .. code-block:: text162163 > set FLASK_ENV=development164 > flask run165 * Serving Flask app "hello"166 * Environment: development167 * Debug mode: on168 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)169 * Restarting with inotify reloader170 * Debugger is active!171 * Debugger PIN: 223-456-919172173 .. group-tab:: Powershell174175 .. code-block:: text176177 > $env:FLASK_ENV = "development"178 > flask run179 * Serving Flask app "hello"180 * Environment: development181 * Debug mode: on182 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)183 * Restarting with inotify reloader184 * Debugger is active!185 * Debugger PIN: 223-456-919186187188Watch Extra Files with the Reloader189~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~190191When using development mode, the reloader will trigger whenever your192Python code or imported modules change. The reloader can watch193additional files with the ``--extra-files`` option, or the194``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are195separated with ``:``, or ``;`` on Windows.196197.. tabs::198199 .. group-tab:: Bash200201 .. code-block:: text202203 $ flask run --extra-files file1:dirA/file2:dirB/204 # or205 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/206 $ flask run207 * Running on http://127.0.0.1:8000/208 * Detected change in '/path/to/file1', reloading209210 .. group-tab:: CMD211212 .. code-block:: text213214 > flask run --extra-files file1:dirA/file2:dirB/215 # or216 > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/217 > flask run218 * Running on http://127.0.0.1:8000/219 * Detected change in '/path/to/file1', reloading220221 .. group-tab:: Powershell222223 .. code-block:: text224225 > flask run --extra-files file1:dirA/file2:dirB/226 # or227 > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"228 > flask run229 * Running on http://127.0.0.1:8000/230 * Detected change in '/path/to/file1', reloading231232233Debug Mode234----------235236Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,237as described above. If you want to control debug mode separately, use238:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.239240241.. _dotenv:242243Environment Variables From dotenv244---------------------------------245246Rather than setting ``FLASK_APP`` each time you open a new terminal, you can247use Flask's dotenv support to set environment variables automatically.248249If `python-dotenv`_ is installed, running the ``flask`` command will set250environment variables defined in the files :file:`.env` and :file:`.flaskenv`.251This can be used to avoid having to set ``FLASK_APP`` manually every time you252open a new terminal, and to set configuration using environment variables253similar to how some deployment services work.254255Variables set on the command line are used over those set in :file:`.env`,256which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be257used for public variables, such as ``FLASK_APP``, while :file:`.env` should not258be committed to your repository so that it can set private variables.259260Directories are scanned upwards from the directory you call ``flask``261from to locate the files. The current working directory will be set to the262location of the file, with the assumption that that is the top level project263directory.264265The files are only loaded by the ``flask`` command or calling266:meth:`~Flask.run`. If you would like to load these files when running in267production, you should call :func:`~cli.load_dotenv` manually.268269.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme270271272Setting Command Options273~~~~~~~~~~~~~~~~~~~~~~~274275Click is configured to load default values for command options from276environment variables. The variables use the pattern277``FLASK_COMMAND_OPTION``. For example, to set the port for the run278command, instead of ``flask run --port 8000``:279280.. tabs::281282 .. group-tab:: Bash283284 .. code-block:: text285286 $ export FLASK_RUN_PORT=8000287 $ flask run288 * Running on http://127.0.0.1:8000/289290 .. group-tab:: CMD291292 .. code-block:: text293294 > set FLASK_RUN_PORT=8000295 > flask run296 * Running on http://127.0.0.1:8000/297298 .. group-tab:: Powershell299300 .. code-block:: text301302 > $env:FLASK_RUN_PORT = 8000303 > flask run304 * Running on http://127.0.0.1:8000/305306These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to307control default command options.308309310Disable dotenv311~~~~~~~~~~~~~~312313The ``flask`` command will show a message if it detects dotenv files but314python-dotenv is not installed.315316.. code-block:: bash317318 $ flask run319 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.320321You can tell Flask not to load dotenv files even when python-dotenv is322installed by setting the ``FLASK_SKIP_DOTENV`` environment variable.323This can be useful if you want to load them manually, or if you're using324a project runner that loads them already. Keep in mind that the325environment variables must be set before the app loads or it won't326configure as expected.327328.. tabs::329330 .. group-tab:: Bash331332 .. code-block:: text333334 $ export FLASK_SKIP_DOTENV=1335 $ flask run336337 .. group-tab:: CMD338339 .. code-block:: text340341 > set FLASK_SKIP_DOTENV=1342 > flask run343344 .. group-tab:: Powershell345346 .. code-block:: text347348 > $env:FLASK_SKIP_DOTENV = 1349 > flask run350351352Environment Variables From virtualenv353-------------------------------------354355If you do not want to install dotenv support, you can still set environment356variables by adding them to the end of the virtualenv's :file:`activate`357script. Activating the virtualenv will set the variables.358359.. tabs::360361 .. group-tab:: Bash362363 Unix Bash, :file:`venv/bin/activate`::364365 $ export FLASK_APP=hello366367 .. group-tab:: CMD368369 Windows CMD, :file:`venv\\Scripts\\activate.bat`::370371 > set FLASK_APP=hello372373 .. group-tab:: Powershell374375 Windows Powershell, :file:`venv\\Scripts\\activate.ps1`::376377 > $env:FLASK_APP = "hello"378379It is preferred to use dotenv support over this, since :file:`.flaskenv` can be380committed to the repository so that it works automatically wherever the project381is checked out.382383384Custom Commands385---------------386387The ``flask`` command is implemented using `Click`_. See that project's388documentation for full information about writing commands.389390This example adds the command ``create-user`` that takes the argument391``name``. ::392393 import click394 from flask import Flask395396 app = Flask(__name__)397398 @app.cli.command("create-user")399 @click.argument("name")400 def create_user(name):401 ...402403::404405 $ flask create-user admin406407This example adds the same command, but as ``user create``, a command in a408group. This is useful if you want to organize multiple related commands. ::409410 import click411 from flask import Flask412 from flask.cli import AppGroup413414 app = Flask(__name__)415 user_cli = AppGroup('user')416417 @user_cli.command('create')418 @click.argument('name')419 def create_user(name):420 ...421422 app.cli.add_command(user_cli)423424::425426 $ flask user create demo427428See :ref:`testing-cli` for an overview of how to test your custom429commands.430431432Registering Commands with Blueprints433~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~434435If your application uses blueprints, you can optionally register CLI436commands directly onto them. When your blueprint is registered onto your437application, the associated commands will be available to the ``flask``438command. By default, those commands will be nested in a group matching439the name of the blueprint.440441.. code-block:: python442443 from flask import Blueprint444445 bp = Blueprint('students', __name__)446447 @bp.cli.command('create')448 @click.argument('name')449 def create(name):450 ...451452 app.register_blueprint(bp)453454.. code-block:: text455456 $ flask students create alice457458You can alter the group name by specifying the ``cli_group`` parameter459when creating the :class:`Blueprint` object, or later with460:meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`.461The following are equivalent:462463.. code-block:: python464465 bp = Blueprint('students', __name__, cli_group='other')466 # or467 app.register_blueprint(bp, cli_group='other')468469.. code-block:: text470471 $ flask other create alice472473Specifying ``cli_group=None`` will remove the nesting and merge the474commands directly to the application's level:475476.. code-block:: python477478 bp = Blueprint('students', __name__, cli_group=None)479 # or480 app.register_blueprint(bp, cli_group=None)481482.. code-block:: text483484 $ flask create alice485486487Application Context488~~~~~~~~~~~~~~~~~~~489490Commands added using the Flask app's :attr:`~Flask.cli`491:meth:`~cli.AppGroup.command` decorator will be executed with an application492context pushed, so your command and extensions have access to the app and its493configuration. If you create a command using the Click :func:`~click.command`494decorator instead of the Flask decorator, you can use495:func:`~cli.with_appcontext` to get the same behavior. ::496497 import click498 from flask.cli import with_appcontext499500 @click.command()501 @with_appcontext502 def do_work():503 ...504505 app.cli.add_command(do_work)506507If you're sure a command doesn't need the context, you can disable it::508509 @app.cli.command(with_appcontext=False)510 def do_work():511 ...512513514Plugins515-------516517Flask will automatically load commands specified in the ``flask.commands``518`entry point`_. This is useful for extensions that want to add commands when519they are installed. Entry points are specified in :file:`setup.py` ::520521 from setuptools import setup522523 setup(524 name='flask-my-extension',525 ...,526 entry_points={527 'flask.commands': [528 'my-command=flask_my_extension.commands:cli'529 ],530 },531 )532533534.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points535536Inside :file:`flask_my_extension/commands.py` you can then export a Click537object::538539 import click540541 @click.command()542 def cli():543 ...544545Once that package is installed in the same virtualenv as your Flask project,546you can run ``flask my-command`` to invoke the command.547548549.. _custom-scripts:550551Custom Scripts552--------------553554When you are using the app factory pattern, it may be more convenient to define555your own Click script. Instead of using ``FLASK_APP`` and letting Flask load556your application, you can create your own Click object and export it as a557`console script`_ entry point.558559Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::560561 import click562 from flask import Flask563 from flask.cli import FlaskGroup564565 def create_app():566 app = Flask('wiki')567 # other setup568 return app569570 @click.group(cls=FlaskGroup, create_app=create_app)571 def cli():572 """Management script for the Wiki application."""573574Define the entry point in :file:`setup.py`::575576 from setuptools import setup577578 setup(579 name='flask-my-extension',580 ...,581 entry_points={582 'console_scripts': [583 'wiki=wiki:cli'584 ],585 },586 )587588Install the application in the virtualenv in editable mode and the custom589script is available. Note that you don't need to set ``FLASK_APP``. ::590591 $ pip install -e .592 $ wiki run593594.. admonition:: Errors in Custom Scripts595596 When using a custom script, if you introduce an error in your597 module-level code, the reloader will fail because it can no longer598 load the entry point.599600 The ``flask`` command, being separate from your code, does not have601 this issue and is recommended in most cases.602603.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts604605606PyCharm Integration607-------------------608609PyCharm Professional provides a special Flask run configuration. For610the Community Edition, we need to configure it to call the ``flask run``611CLI command with the correct environment variables. These instructions612should be similar for any other IDE you might want to use.613614In PyCharm, with your project open, click on *Run* from the menu bar and615go to *Edit Configurations*. You'll be greeted by a screen similar to616this:617618.. image:: _static/pycharm-runconfig.png619 :align: center620 :class: screenshot621 :alt: Screenshot of PyCharms's run configuration settings.622623There's quite a few options to change, but once we've done it for one624command, we can easily copy the entire configuration and make a single625tweak to give us access to other commands, including any custom ones you626may implement yourself.627628Click the + (*Add New Configuration*) button and select *Python*. Give629the configuration a name such as "flask run". For the ``flask run``630command, check "Single instance only" since you can't run the server631more than once at the same time.632633Select *Module name* from the dropdown (**A**) then input ``flask``.634635The *Parameters* field (**B**) is set to the CLI command to execute636(with any arguments). In this example we use ``run``, which will run637the development server.638639You can skip this next step if you're using :ref:`dotenv`. We need to640add an environment variable (**C**) to identify our application. Click641on the browse button and add an entry with ``FLASK_APP`` on the left and642the Python import or file on the right (``hello`` for example). Add an643entry with ``FLASK_ENV`` and set it to ``development``.644645Next we need to set the working directory (**D**) to be the folder where646our application resides.647648If you have installed your project as a package in your virtualenv, you649may untick the *PYTHONPATH* options (**E**). This will more accurately650match how you deploy the app later.651652Click *Apply* to save the configuration, or *OK* to save and close the653window. Select the configuration in the main PyCharm window and click654the play button next to it to run the server.655656Now that we have a configuration which runs ``flask run`` from within657PyCharm, we can copy that configuration and alter the *Script* argument658to run a different CLI command, e.g. ``flask shell``.