cli.rst
This file
Path
docs/cli.rst
335 lines · 12.1 KiB
Last changed by
Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
History of this fileTake it
The walk stopped after 200 commits: lines older than 2f60124 point at it.
Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 1–5why, one step back1.. _cli:23Command Line Interface4======================5resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 6why, one step back6.. versionadded:: 0.11Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 7–9why, one step back78.. currentmodule:: flask9resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 10why, one step back10One of the nice new features in Flask 0.11 is the built-in integration ofRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 11–17why, one step back11the `click <http://click.pocoo.org/>`_ command line interface. This12enables a wide range of new features for the Flask ecosystem and your own13applications.1415Basic Usage16-----------17resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 18–21why, one step back18After installation of Flask you will now find a :command:`flask` script19installed into your virtualenv. If you don't want to install Flask or you20have a special use-case you can also use ``python -m flask`` to accomplish21exactly the same.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 22–27why, one step back2223The 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.27Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a
lines 28–35why, one step back28For the :command:`flask` script to work, an application needs to be discovered.29Flask looks for a module named :file:`wsgi.py` or :file:`app.py` by default,30and if it finds one it assumes the application is defined in it.3132You can instruct Flask to look for the application in a different module by33exporting the ``FLASK_APP`` environment variable. It can be either set to an34import path or to a filename of a Python module that contains a Flask35application.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 36–37why, one step back3637In that imported file the name of the app needs to be called ``app`` orresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 38–40why, one step back38optionally be specified after a colon. For instance39``mymodule:application`` would tell it to use the `application` object in40the :file:`mymodule.py` file.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 41why, one step back41resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 42–43why, one step back42Given a :file:`hello.py` file with the application in it named ``app``43this is how it can be run.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 44–49why, one step back4445Environment variables (On Windows use ``set`` instead of ``export``)::4647 export FLASK_APP=hello48 flask run49resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 50why, one step back50Or with a filename::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 51why, one step back51resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 52–53why, one step back52 export FLASK_APP=/path/to/hello.py53 flask runRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 54–62why, one step back5455Virtualenv Integration56----------------------5758If you are constantly working with a virtualenv you can also put the59``export FLASK_APP`` into your ``activate`` script by adding it to the60bottom of the file. That way every time you activate your virtualenv you61automatically also activate the correct application name.62resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 63–74why, one step back63Edit the activate script for the shell you use. For example:6465Unix Bash: ``venv/bin/activate``::6667 FLASK_APP=hello68 export FLASK_APP6970Windows CMD.exe: ``venv\Scripts\activate.bat``::7172 set "FLASK_APP=hello"73 :END74Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 75–77why, one step back75Debug Flag76----------77resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 78–80why, one step back78The :command:`flask` script can also be instructed to enable the debug79mode of the application automatically by exporting ``FLASK_DEBUG``. If80set to ``1`` debug is enabled or ``0`` disables it::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 81why, one step back81resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 82–83why, one step back82 export FLASK_DEBUG=183Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 84–88why, one step back84Running a Shell85---------------8687To run an interactive Python shell you can use the ``shell`` command::88resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 89why, one step back89 flask shellRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 90–99why, one step back9091This will start up an interactive Python shell, setup the correct92application context and setup the local variables in the shell. This is93done by invoking the :meth:`Flask.make_shell_context` method of the94application. By default you have access to your ``app`` and :data:`g`.9596Custom Commands97---------------9899If you want to add more commands to the shell script you can do thisMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 100–101why, one step back100easily. For instance if you want a shell command to initialize the database you101can do this::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 102why, one step back102resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 103why, one step back103 import clickRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 104–110why, one step back104 from flask import Flask105106 app = Flask(__name__)107108 @app.cli.command()109 def initdb():110 """Initialize the database."""resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 111why, one step back111 click.echo('Init the db')Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 112–114why, one step back112113The command will then show up on the command line::114resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 115why, one step back115 $ flask initdbRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 116–125why, one step back116 Init the db117118Application Context119-------------------120121Most commands operate on the application so it makes a lot of sense if122they have the application context setup. Because of this, if you register123a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the124callback will automatically be wrapped through :func:`cli.with_appcontext`125which informs the cli system to ensure that an application context is setMerge pull request #1217 from jeffwidman/patch-1Markus Unterwaditzerbefore adoption7b3e52b
line 126why, one step back126up. This behavior is not available if a command is added later withRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 127–134why, one step back127:func:`~click.Group.add_command` or through other means.128129It can also be disabled by passing ``with_appcontext=False`` to the130decorator::131132 @app.cli.command(with_appcontext=False)133 def example():134 passMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 135–163why, one step back135136137.. _dotenv:138139Loading Environment Variables From ``.env`` Files140-------------------------------------------------141142If `python-dotenv`_ is installed, running the :command:`flask` command will set143environment variables defined in the files :file:`.env` and :file:`.flaskenv`.144This can be used to avoid having to set ``FLASK_APP`` manually every time you145open a new terminal, and to set configuration using environment variables146similar to how some deployment services work.147148Variables set on the command line are used over those set in :file:`.env`,149which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be150used for public variables, such as ``FLASK_APP``, while :file:`.env` should not151be committed to your repository so that it can set private variables.152153Directories are scanned upwards from the directory you call :command:`flask`154from to locate the files. The current working directory will be set to the155location of the file, with the assumption that that is the top level project156directory.157158The files are only loaded by the :command:`flask` command or calling159:meth:`~flask.Flask.run`. If you would like to load these files when running in160production, you should call :func:`~flask.cli.load_dotenv` manually.161162.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme163Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 164–168why, one step back164165Factory Functions166-----------------167168In case you are using factory functions to create your application (seeresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 169–170why, one step back169:ref:`app-factories`) you will discover that the :command:`flask` command170cannot work with them directly. Flask won't be able to figure out how toRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 171–172why, one step back171instantiate your application properly by itself. Because of this reason172the recommendation is to create a separate file that instantiatesresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 173–174why, one step back173applications. This is not the only way to make this work. Another is the174:ref:`custom-scripts` support.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 175–179why, one step back175176For instance if you have a factory function that creates an application177from a filename you could make a separate file that creates such an178application from an environment variable.179Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 180why, one step back180This could be a file named :file:`autoapp.py` with these contents::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 181–185why, one step back181182 import os183 from yourapplication import create_app184 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])185resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 186–187why, one step back186Once this has happened you can make the :command:`flask` command automatically187pick it up::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 188–191why, one step back188189 export YOURAPPLICATION_CONFIG=/path/to/config.cfg190 export FLASK_APP=/path/to/autoapp.py191Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 192why, one step back192From this point onwards :command:`flask` will find your application.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 193–198why, one step back193194.. _custom-scripts:195196Custom Scripts197--------------198resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 199–201why, one step back199While the most common way is to use the :command:`flask` command, you can200also make your own "driver scripts". Since Flask uses click for the201scripts there is no reason you cannot hook these scripts into any clickRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 202–208why, one step back202application. There is one big caveat and that is, that commands203registered to :attr:`Flask.cli` will expect to be (indirectly at least)204launched from a :class:`flask.cli.FlaskGroup` click group. This is205necessary so that the commands know which Flask application they have to206work with.207208To understand why you might want custom scripts you need to understand howresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 209–213why, one step back209click finds and executes the Flask application. If you use the210:command:`flask` script you specify the application to work with on the211command line or environment variable as an import name. This is simple212but it has some limitations. Primarily it does not work with application213factory functions (see :ref:`app-factories`).Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 214–219why, one step back214215With a custom script you don't have this problem as you can fully216customize how the application will be created. This is very useful if you217write reusable applications that you want to ship to users and they should218be presented with a custom management script.219Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 220why, one step back220To explain all of this, here is an example :file:`manage.py` script thatRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 221–223why, one step back221manages a hypothetical wiki application. We will go through the details222afterwards::223resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 224why, one step back224 import osRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 225why, one step back225 import clickresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 226why, one step back226 from flask.cli import FlaskGroupRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 227–229why, one step back227228 def create_wiki_app(info):229 from yourwiki import create_appresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 230–231why, one step back230 return create_app(231 config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 232–233why, one step back232233 @click.group(cls=FlaskGroup, create_app=create_wiki_app)resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 234why, one step back234 def cli():Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 235–244why, one step back235 """This is a management script for the wiki application."""236237 if __name__ == '__main__':238 cli()239240That's a lot of code for not much, so let's go through all parts step by241step.2422431. First we import the ``click`` library as well as the click extensions244 from the ``flask.cli`` package. Primarily we are here interestedresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 245why, one step back245 in the :class:`~flask.cli.FlaskGroup` click group.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 246why, one step back2462. The next thing we do is defining a function that is invoked with theresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 247why, one step back247 script info object (:class:`~flask.cli.ScriptInfo`) from Flask and itsRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 248–249why, one step back248 purpose is to fully import and create the application. This can249 either directly import an application object or create it (seeresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 250–251why, one step back250 :ref:`app-factories`). In this case we load the config from an251 environment variable.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 252–257why, one step back2523. Next step is to create a :class:`FlaskGroup`. In this case we just253 make an empty function with a help doc string that just does nothing254 and then pass the ``create_wiki_app`` function as a factory function.255256 Whenever click now needs to operate on a Flask application it will257 call that function with the script info and ask for it to be created.resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 258why, one step back2584. All is rounded up by invoking the script.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 259why, one step back259resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 260–261why, one step back260CLI Plugins261-----------Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 262why, one step back262resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 263–267why, one step back263Flask extensions can always patch the :attr:`Flask.cli` instance with more264commands if they want. However there is a second way to add CLI plugins265to Flask which is through ``setuptools``. If you make a Python package that266should export a Flask command line plugin you can ship a :file:`setup.py` file267that declares an entrypoint that points to a click command:Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 268why, one step back268resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 269why, one step back269Example :file:`setup.py`::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 270why, one step back270resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 271why, one step back271 from setuptools import setupRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 272why, one step back272resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 273–280why, one step back273 setup(274 name='flask-my-extension',275 ...276 entry_points='''277 [flask.commands]278 my-command=mypackage.commands:cli279 ''',280 )Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 281why, one step back281resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 282–335why, one step back282Inside :file:`mypackage/commands.py` you can then export a Click object::283284 import click285286 @click.command()287 def cli():288 """This is an example command."""289290Once that package is installed in the same virtualenv as Flask itself you291can run ``flask my-command`` to invoke your command. This is useful to292provide extra functionality that Flask itself cannot ship.293294PyCharm Integration295-------------------296297The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,298so we have to do a few tweaks to get them working smoothly.299300In your PyCharm application, with your project open, click on *Run*301from the menu bar and go to *Edit Configurations*. You’ll be greeted by a302screen similar to this:303304.. image:: _static/pycharm-runconfig.png305 :align: center306 :class: screenshot307 :alt: screenshot of pycharm's run configuration settings308309There’s quite a few options to change, but don’t worry— once we’ve done it310for one command, we can easily copy the entire configuration and make a311single tweak to give us access to other flask cli commands, including312any custom ones you may implement yourself.313314For the *Script* input (**A**), we want to navigate to the virtual environment315we’re using for our project and within that folder we want to pick the ``flask``316file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if317you're on Windows.318319The *Script Parameter* field (**B**) is set to the cli command you wish to320execute, in this example we use ``run`` which will run our development server.321322We need to add an environment variable (**C**) to identify our application.323Click on the browse button and add an entry with ``FLASK_APP`` on the324left and the name of the python file, or package on the right325(``app.py`` for example).326327Next we need to set the working directory (**D**) to be the same folder where328our application file or package resides.329330Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a331good descriptive name, such as “Run Flask Server” and click *Apply*.332333Now that we have on run configuration which implements ``flask run`` from within334PyCharm, we can simply copy that configuration and alter the script argument335to run a different cli command, e.g. ``flask shell``.