cli.rst
This file
Path
docs/cli.rst
241 lines · 9.3 KiB
Last changed by
Merge pull request #1057 from IanConnolly/doc-fixKenneth Reitzbefore adoptionda1c1f0
History of this fileTake it
1.. _cli:23Command Line Interface4======================56.. versionadded:: 1.078.. currentmodule:: flask910One of the nice new features in Flask 1.0 is the built-in integration of11the `click <http://click.pocoo.org/>`_ command line interface. This12enables a wide range of new features for the Flask ecosystem and your own13applications.1415Basic Usage16-----------1718After installation of Flask you will now find a ``flask`` script installed19into your virtualenv. If you don't want to install Flask or you have a20special use-case you can also use ``python -m flask`` to accomplish exactly21the same.2223The way this script works is by providing access to all the commands on24your Flask application's :attr:`Flask.cli` instance as well as some25built-in commands that are always there. Flask extensions can also26register more commands there if they desire so.2728For the ``flask`` script to work, an application needs to be discovered.29The two most common ways are either an environment variable30(``FLASK_APP``) or the ``--app`` / ``-a`` parameter. It should be the31import path for your application or the path to a Python file. In the32latter case Flask will attempt to setup the Python path for you33automatically and discover the module name but that might not always work.3435In that imported file the name of the app needs to be called ``app`` or36optionally be specified after a colon.3738Given a ``hello.py`` file with the application in it named ``app`` this is39how it can be run.4041Environment variables (On Windows use ``set`` instead of ``export``)::4243 export FLASK_APP=hello44 flask run4546Parameters::4748 flask --app=hello run4950File names::5152 flask --app=hello.py run5354Virtualenv Integration55----------------------5657If you are constantly working with a virtualenv you can also put the58``export FLASK_APP`` into your ``activate`` script by adding it to the59bottom of the file. That way every time you activate your virtualenv you60automatically also activate the correct application name.6162Debug Flag63----------6465The ``flask`` script can be run with ``--debug`` or ``--no-debug`` to66automatically flip the debug flag of the application. This can also be67configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.6869Running a Shell70---------------7172To run an interactive Python shell you can use the ``shell`` command::7374 flask --app=hello shell7576This will start up an interactive Python shell, setup the correct77application context and setup the local variables in the shell. This is78done by invoking the :meth:`Flask.make_shell_context` method of the79application. By default you have access to your ``app`` and :data:`g`.8081Custom Commands82---------------8384If you want to add more commands to the shell script you can do this85easily. Flask uses `click`_ for the command interface which makes86creating custom commands very easy. For instance if you want a shell87command to initialize the database you can do this::8889 from flask import Flask9091 app = Flask(__name__)9293 @app.cli.command()94 def initdb():95 """Initialize the database."""96 print 'Init the db'9798The command will then show up on the command line::99100 $ flask -a hello.py initdb101 Init the db102103Factory Functions104-----------------105106In case you are using factory functions to create your application (see107:ref:`app-factories`) you will discover that the ``flask`` command cannot108work with them directly. Flask won't be able to figure out how to109instantiate your application properly by itself. Because of this reason110the recommendation is to create a separate file that instantiates111applications. This is by far not the only way to make this work. Another112is the :ref:`custom-scripts` support.113114For instance if you have a factory function that creates an application115from a filename you could make a separate file that creates such an116application from an environment variable.117118This could be a file named ``autoapp.py`` with these contents::119120 import os121 from yourapplication import create_app122 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])123124Once this has happened you can make the flask command automatically pick125it up::126127 export YOURAPPLICATION_CONFIG=/path/to/config.cfg128 export FLASK_APP=/path/to/autoapp.py129130From this point onwards ``flask`` will find your application.131132.. _custom-scripts:133134Custom Scripts135--------------136137While the most common way is to use the ``flask`` command, you can also138make your own "driver scripts". Since Flask uses click for the scripts139there is no reason you cannot hook these scripts into any click140application. There is one big caveat and that is, that commands141registered to :attr:`Flask.cli` will expect to be (indirectly at least)142launched from a :class:`flask.cli.FlaskGroup` click group. This is143necessary so that the commands know which Flask application they have to144work with.145146To understand why you might want custom scripts you need to understand how147click finds and executes the Flask application. If you use the ``flask``148script you specify the application to work with on the command line or149environment variable as an import name. This is simple but it has some150limitations. Primarily it does not work with application factory151functions (see :ref:`app-factories`).152153With a custom script you don't have this problem as you can fully154customize how the application will be created. This is very useful if you155write reusable applications that you want to ship to users and they should156be presented with a custom management script.157158If you are used to writing click applications this will look familiar but159at the same time, slightly different because of how commands are loaded.160We won't go into detail now about the differences but if you are curious161you can have a look at the :ref:`script-info-object` section to learn all162about it.163164To explain all of this, here is an example ``manage.py`` script that165manages a hypothetical wiki application. We will go through the details166afterwards::167168 import click169 from flask.cli import FlaskGroup, script_info_option170171 def create_wiki_app(info):172 from yourwiki import create_app173 config = info.data.get('config') or 'wikiconfig.py'174 return create_app(config=config)175176 @click.group(cls=FlaskGroup, create_app=create_wiki_app)177 @script_info_option('--config', script_info_key='config')178 def cli(**params):179 """This is a management script for the wiki application."""180181 if __name__ == '__main__':182 cli()183184That's a lot of code for not much, so let's go through all parts step by185step.1861871. First we import the ``click`` library as well as the click extensions188 from the ``flask.cli`` package. Primarily we are here interested189 in the :class:`~flask.cli.FlaskGroup` click group and the190 :func:`~flask.cli.script_info_option` decorator.1912. The next thing we do is defining a function that is invoked with the192 script info object (:ref:`script-info-object`) from Flask and its193 purpose is to fully import and create the application. This can194 either directly import an application object or create it (see195 :ref:`app-factories`).196197 What is ``data.info``? It's a dictionary of arbitrary data on the198 script info that can be filled by options or through other means. We199 will come back to this later.2003. Next step is to create a :class:`FlaskGroup`. In this case we just201 make an empty function with a help doc string that just does nothing202 and then pass the ``create_wiki_app`` function as a factory function.203204 Whenever click now needs to operate on a Flask application it will205 call that function with the script info and ask for it to be created.2064. In step 2 you could see that the config is passed to the actual207 creation function. This config comes from the :func:`script_info_option`208 decorator for the main script. It accepts a ``--config`` option and209 then stores it in the script info so we can use it to create the210 application.2115. All is rounded up by invoking the script.212213.. _script-info-object:214215The Script Info216---------------217218The Flask script integration might be confusing at first, but there is a reason219why it's done this way. The reason for this is that Flask wants to220both provide custom commands to click as well as not loading your221application unless it has to. The reason for this is added flexibility.222223This way an application can provide custom commands, but even in the224absence of an application the ``flask`` script is still operational on a225basic level. In addition to that it means that the individual commands226have the option to avoid creating an instance of the Flask application227unless required. This is very useful as it allows the server commands for228instance to load the application on a first request instead of229immediately, therefore giving a better debug experience.230231All of this is provided through the :class:`flask.cli.ScriptInfo` object232and some helper utilities around. The basic way it operates is that when233the :class:`flask.cli.FlaskGroup` executes as a script it creates a script234info and keeps it around. From that point onwards modifications on the235script info can be done through click options. To simplify this pattern236the :func:`flask.cli.script_info_option` decorator was added.237238One Flask actually needs the individual Flask application it will invoke239the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the240server starts, when the shell is launched or when the script looks for an241application-provided click command.