rewrite cli docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
reflects the current FLASK_APP detection
authored by David Lord · committed by David Lord · parent 5436ddd · Browse files · 3 files·+288 added−235 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+288 added−235 removed
- other:+288 added−235 removed
Provenance
- Commit
9bc329c- Tree
f35bdd0- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
5436ddd
3 files changed+288 added−235 removed
modified:docs/cli.rst+263 added-215 removed
1+.. currentmodule:: flask2+3 .. _cli:4 5 Command Line Interface6 ======================7 6-.. versionadded:: 0.118+Installing Flask installs the ``flask`` script, a `Click`_ command line9+interface, in your virtualenv. Executed from the terminal, this script gives10+access to built-in, extension, and application-defined commands. The ``--help``11+option will give more information about any commands and options.12 8-.. currentmodule:: flask13+.. _Click: http://click.pocoo.org/14 10-One of the nice new features in Flask 0.11 is the built-in integration of11-the `click <http://click.pocoo.org/>`_ command line interface. This12-enables a wide range of new features for the Flask ecosystem and your own13-applications.15 15-Basic Usage16------------16+Application Discovery17+---------------------18 18-After installation of Flask you will now find a :command:`flask` script19-installed into your virtualenv. If you don't want to install Flask or you20-have a special use-case you can also use ``python -m flask`` to accomplish21-exactly the same.19+The ``flask`` command is installed by Flask, not your application; it must be20+told where to find your application in order to use it. The ``FLASK_APP``21+environment variable is used to specify how to load the application.22 23-The way this script works is by providing access to all the commands on24-your Flask application's :attr:`Flask.cli` instance as well as some25-built-in commands that are always there. Flask extensions can also26-register more commands there if they desire so.23+Unix Bash (Linux, Mac, etc.)::24 28-For the :command:`flask` script to work, an application needs to be discovered.29-Flask looks for a module named :file:`wsgi.py` or :file:`app.py` by default,30-and if it finds one it assumes the application is defined in it.25+ $ export FLASK_APP=hello26+ $ flask run27 32-You can instruct Flask to look for the application in a different module by33-exporting the ``FLASK_APP`` environment variable. It can be either set to an34-import path or to a filename of a Python module that contains a Flask35-application.28+Windows CMD::29 37-In that imported file the name of the app needs to be called ``app`` or38-optionally be specified after a colon. For instance39-``mymodule:application`` would tell it to use the `application` object in40-the :file:`mymodule.py` file.30+ > set FLASK_APP=hello31+ > flask run32 42-Given a :file:`hello.py` file with the application in it named ``app``43-this is how it can be run.33+Windows PowerShell::34 45-Environment variables (On Windows use ``set`` instead of ``export``)::35+ > $env:FLASK_APP = "hello"36+ > flask run37 47- export FLASK_APP=hello48- flask run38+While ``FLASK_APP`` supports a variety of options for specifying your39+application, most use cases should be simple. Here are the typical values:40 50-Or with a filename::41+(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.45 52- export FLASK_APP=/path/to/hello.py53- flask run46+``FLASK_APP=hello``47+ The name is imported, automatically detecting an app (``app``) or factory48+ (``create_app``).49 55-Virtualenv Integration56-----------------------50+----51 58-If you are constantly working with a virtualenv you can also put the59-``export FLASK_APP`` into your ``activate`` script by adding it to the60-bottom of the file. That way every time you activate your virtualenv you61-automatically also activate the correct application name.52+``FLASK_APP`` has three parts: an optional path that sets the current working53+directory, a Python file or dotted import path, and an optional variable54+name of the instance or factory. If the name is a factory, it can optionally55+be followed by arguments in parentheses. The following values demonstrate these56+parts:57 63-Edit the activate script for the shell you use. For example:58+``FLASK_APP=src/hello``59+ Sets the current working directory to ``src`` then imports ``hello``.60 65-Unix Bash: ``venv/bin/activate``::61+``FLASK_APP=hello.web``62+ Imports the path ``hello.web``.63 67- FLASK_APP=hello68- export FLASK_APP64+``FLASK_APP=hello:app2``65+ Uses the ``app2`` Flask instance in ``hello``.66 70-Windows CMD.exe: ``venv\Scripts\activate.bat``::67+``FLASK_APP="hello:create_app('dev')"``68+ The ``create_app`` factory in ``hello`` is called with the string ``'dev'``69+ as the argument.70 72- set "FLASK_APP=hello"73- :END71+If ``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 or73+factory.74 75-Debug Flag76-----------75+Within the given import, the command looks for an application instance named76+``app`` or ``application``, then any application instance. If no instance is77+found, the command looks for a factory function named ``create_app`` or78+``make_app`` that returns an instance.79 78-The :command:`flask` script can also be instructed to enable the debug79-mode of the application automatically by exporting ``FLASK_DEBUG``. If80-set to ``1`` debug is enabled or ``0`` disables it::80+When calling an application factory, if the factory takes an argument named81+``info``, then the :class:`~cli.ScriptInfo` instance is passed as a keyword82+argument. If parentheses follow the factory name, their contents are parsed83+as Python literals and passes as arguments to the function. This means that84+strings must still be in quotes.85 82- export FLASK_DEBUG=186 84-Running a Shell85----------------87+Run the Development Server88+--------------------------89 87-To run an interactive Python shell you can use the ``shell`` command::90+The :func:`run <cli.run_command>` command will start the development server. It91+replaces the :meth:`Flask.run` method in most cases. ::92 89- flask shell93+ $ flask run94+ * Serving Flask app "hello"95+ * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)96 91-This will start up an interactive Python shell, setup the correct92-application context and setup the local variables in the shell. This is93-done by invoking the :meth:`Flask.make_shell_context` method of the94-application. By default you have access to your ``app`` and :data:`g`.97+.. 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.101 96-Custom Commands97----------------102 99-If you want to add more commands to the shell script you can do this100-easily. For instance if you want a shell command to initialize the database you101-can do this::103+Open a Shell104+------------105 103- import click104- from flask import Flask106+To explore the data in your application, you can start an interactive Python107+shell with the :func:`shell <cli.shell_command>` command. An application108+context will be active, and the app instance will be imported. ::109 106- app = Flask(__name__)110+ $ 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+ >>>116 108- @app.cli.command()109- def initdb():110- """Initialize the database."""111- click.echo('Init the db')117+Use :meth:`~Flask.shell_context_processor` to add other automatic imports.118 113-The command will then show up on the command line::119 115- $ flask initdb116- Init the db120+Debug Mode121+----------122 118-Application Context119--------------------123+Set the :envvar:`FLASK_DEBUG` environment variable to override the124+application's :attr:`~Flask.debug` flag. The value ``1`` enables it, ``0``125+disables it. Forcing the debug flag on also enables the debugger and reloader126+when running the development server. ::127 121-Most commands operate on the application so it makes a lot of sense if122-they have the application context setup. Because of this, if you register123-a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the124-callback will automatically be wrapped through :func:`cli.with_appcontext`125-which informs the cli system to ensure that an application context is set126-up. This behavior is not available if a command is added later with127-:func:`~click.Group.add_command` or through other means.128+ $ 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-919135 129-It can also be disabled by passing ``with_appcontext=False`` to the130-decorator::136 132- @app.cli.command(with_appcontext=False)133- def example():134- pass135-136-137 .. _dotenv:138 139-Loading Environment Variables From ``.env`` Files140--------------------------------------------------139+Environment Variables From dotenv140+---------------------------------141 142+Rather than setting ``FLASK_APP`` each time you open a new terminal, you can143+use Flask's dotenv support to set environment variables automatically.144+142-If `python-dotenv`_ is installed, running the :command:`flask` command will set145+If `python-dotenv`_ is installed, running the ``flask`` command will set146 environment variables defined in the files :file:`.env` and :file:`.flaskenv`.147 This can be used to avoid having to set ``FLASK_APP`` manually every time you148 open a new terminal, and to set configuration using environment variables149 similar to how some deployment services work.2 unmodified lines152 which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be153 used for public variables, such as ``FLASK_APP``, while :file:`.env` should not154 be committed to your repository so that it can set private variables.155 153-Directories are scanned upwards from the directory you call :command:`flask`156+Directories are scanned upwards from the directory you call ``flask``157 from to locate the files. The current working directory will be set to the158 location of the file, with the assumption that that is the top level project159 directory.160 158-The 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 in160-production, you should call :func:`~flask.cli.load_dotenv` manually.161+The files are only loaded by the ``flask`` command or calling162+:meth:`~Flask.run`. If you would like to load these files when running in163+production, you should call :func:`~cli.load_dotenv` manually.164 165 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme166 167 165-Factory Functions166------------------168+Environment Variables From virtualenv169+-------------------------------------170 168-In case you are using factory functions to create your application (see169-:ref:`app-factories`) you will discover that the :command:`flask` command170-cannot work with them directly. Flask won't be able to figure out how to171-instantiate your application properly by itself. Because of this reason172-the recommendation is to create a separate file that instantiates173-applications. This is not the only way to make this work. Another is the174-:ref:`custom-scripts` support.171+If you do not want to install dotenv support, you can still set environment172+variables by adding them to the end of the virtualenv's :file:`activate`173+script. Activating the virtualenv will set the variables.174 176-For instance if you have a factory function that creates an application177-from a filename you could make a separate file that creates such an178-application from an environment variable.175+Unix Bash, :file:`venv/bin/activate`::176 180-This could be a file named :file:`autoapp.py` with these contents::177+ export FLASK_APP=hello178 182- import os183- from yourapplication import create_app184- app = create_app(os.environ['YOURAPPLICATION_CONFIG'])179+Windows CMD, :file:`venv\Scripts\activate.bat`::180 186-Once this has happened you can make the :command:`flask` command automatically187-pick it up::181+ set FLASK_APP=hello182 189- export YOURAPPLICATION_CONFIG=/path/to/config.cfg190- export FLASK_APP=/path/to/autoapp.py183+It is preferred to use dotenv support over this, since :file:`.flaskenv` can be184+committed to the repository so that it works automatically wherever the project185+is checked out.186 192-From this point onwards :command:`flask` will find your application.187 194-.. _custom-scripts:188+Custom Commands189+---------------190 196-Custom Scripts197---------------191+The ``flask`` command is implemented using `Click`_. See that project's192+documentation for full information about writing commands.193 199-While the most common way is to use the :command:`flask` command, you can200-also make your own "driver scripts". Since Flask uses click for the201-scripts there is no reason you cannot hook these scripts into any click202-application. There is one big caveat and that is, that commands203-registered to :attr:`Flask.cli` will expect to be (indirectly at least)204-launched from a :class:`flask.cli.FlaskGroup` click group. This is205-necessary so that the commands know which Flask application they have to206-work with.194+This example adds the command ``create_user`` that takes the argument195+``name``. ::196 208-To understand why you might want custom scripts you need to understand how209-click finds and executes the Flask application. If you use the210-:command:`flask` script you specify the application to work with on the211-command line or environment variable as an import name. This is simple212-but it has some limitations. Primarily it does not work with application213-factory functions (see :ref:`app-factories`).197+ import click198+ from flask import Flask199 215-With a custom script you don't have this problem as you can fully216-customize how the application will be created. This is very useful if you217-write reusable applications that you want to ship to users and they should218-be presented with a custom management script.200+ app = Flask(__name__)201 220-To explain all of this, here is an example :file:`manage.py` script that221-manages a hypothetical wiki application. We will go through the details222-afterwards::202+ @app.cli.command()203+ @click.argument('name')204+ def create_user(name):205+ ...206 224- import os207+::208+209+ flask create_user admin210+211+This example adds the same command, but as ``user create``, a command in a212+group. This is useful if you want to organize multiple related commands. ::213+214 import click215+ from flask import Flask226- from flask.cli import FlaskGroup216+ from flask.cli import AppGroup217 228- def create_wiki_app(info):229- from yourwiki import create_app230- return create_app(231- config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))218+ app = Flask(__name__)219+ user_cli = AppGroup('user')220 233- @click.group(cls=FlaskGroup, create_app=create_wiki_app)234- def cli():235- """This is a management script for the wiki application."""221+ @user_cli.command('create')222+ @click.argument('name')223+ def create_user(name):224+ ...225 237- if __name__ == '__main__':238- cli()226+ app.cli.add_command(user_cli)227 240-That's a lot of code for not much, so let's go through all parts step by241-step.228+::229 243-1. First we import the ``click`` library as well as the click extensions244- from the ``flask.cli`` package. Primarily we are here interested245- in the :class:`~flask.cli.FlaskGroup` click group.246-2. The next thing we do is defining a function that is invoked with the247- script info object (:class:`~flask.cli.ScriptInfo`) from Flask and its248- purpose is to fully import and create the application. This can249- either directly import an application object or create it (see250- :ref:`app-factories`). In this case we load the config from an251- environment variable.252-3. 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.230+ flask user create demo231 256- 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.258-4. All is rounded up by invoking the script.232 260-CLI Plugins261------------233+Application Context234+~~~~~~~~~~~~~~~~~~~235 263-Flask extensions can always patch the :attr:`Flask.cli` instance with more264-commands if they want. However there is a second way to add CLI plugins265-to Flask which is through ``setuptools``. If you make a Python package that266-should export a Flask command line plugin you can ship a :file:`setup.py` file267-that declares an entrypoint that points to a click command:236+Commands added using the Flask app's :attr:`~Flask.cli`237+:meth:`~cli.AppGroup.command` decorator will be executed with an application238+context pushed, so your command and extensions have access to the app and its239+configuration. If you create a command using the Click :func:`~click.command`240+decorator instead of the Flask decorator, you can use241+:func:`~cli.with_appcontext` to get the same behavior. ::242 269-Example :file:`setup.py`::243+ import click244+ from flask.cli import with_appcontext245 246+ @click.command247+ @with_appcontext248+ def do_work():249+ ...250+251+ app.cli.add_command(do_work)252+253+If you're sure a command doesn't need the context, you can disable it::254+255+ @app.cli.command(with_appcontext=False)256+ def do_work():257+ ...258+259+260+Plugins261+-------262+263+Flask will automatically load commands specified in the ``flask.commands``264+`entry point`_. This is useful for extensions that want to add commands when265+they are installed. Entry points are specified in :file:`setup.py` ::266+267 from setuptools import setup268 269 setup(270 name='flask-my-extension',275- ...276- entry_points='''277- [flask.commands]278- my-command=mypackage.commands:cli279- ''',271+ ...,272+ entry_points={273+ 'flask.commands': [274+ 'my-command=flask_my_extension.commands:cli'275+ ],276+ },277 )278 282-Inside :file:`mypackage/commands.py` you can then export a Click object::279 280+.. _entry point: https://packaging.python.org/tutorials/distributing-packages/#entry-points281+282+Inside :file:`flask_my_extension/commands.py` you can then export a Click283+object::284+285 import click286 287 @click.command()288 def cli():288- """This is an example command."""289+ ...290 290-Once that package is installed in the same virtualenv as Flask itself you291-can run ``flask my-command`` to invoke your command. This is useful to292-provide extra functionality that Flask itself cannot ship.291+Once that package is installed in the same virtualenv as your Flask project,292+you can run ``flask my-command`` to invoke the command.293 294+295+.. _custom-scripts:296+297+Custom Scripts298+--------------299+300+When you are using the app factory pattern, it may be more convenient to define301+your own Click script. Instead of using ``FLASK_APP`` and letting Flask load302+your application, you can create your own Click object and export it as a303+`console script`_ entry point.304+305+Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::306+307+ import click308+ from flask import Flask309+ from flask.cli import FlaskGroup310+311+ def create_app():312+ app = Flask('wiki')313+ # other setup314+ return app315+316+ @click.group(cls=FlaskGroup, create_app=create_app)317+ def cli():318+ """Management script for the Wiki application."""319+320+Define the entry point in :file:`setup.py`::321+322+ from setuptools import setup323+324+ setup(325+ name='flask-my-extension',326+ ...,327+ entry_points={328+ 'console_scripts': [329+ 'wiki=wiki:cli'330+ ],331+ },332+ )333+334+Install the application in the virtualenv in editable mode and the custom335+script is available. Note that you don't need to set ``FLASK_APP``. ::336+337+ $ pip install -e .338+ $ wiki run339+340+.. _console script: https://packaging.python.org/tutorials/distributing-packages/#console-scripts341+342+343 PyCharm Integration344 -------------------345 297-The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,298-so we have to do a few tweaks to get them working smoothly.346+The new Flask CLI features aren't yet fully integrated into the PyCharm IDE,347+so we have to do a few tweaks to get them working smoothly. These instructions348+should be similar for any other IDE you might want to use.349 300-In your PyCharm application, with your project open, click on *Run*301-from the menu bar and go to *Edit Configurations*. You’ll be greeted by a302-screen similar to this:350+In 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:352 353 .. image:: _static/pycharm-runconfig.png354 :align: center355 :class: screenshot356 :alt: screenshot of pycharm's run configuration settings357 309-There’s quite a few options to change, but don’t worry— once we’ve done it310-for one command, we can easily copy the entire configuration and make a311-single tweak to give us access to other flask cli commands, including312-any custom ones you may implement yourself.358+There's quite a few options to change, but once we've done it for one command,359+we can easily copy the entire configuration and make a single tweak to give us360+access to other commands, including any custom ones you may implement yourself.361 314-For the *Script* input (**A**), we want to navigate to the virtual environment315-we’re using for our project and within that folder we want to pick the ``flask``316-file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if317-you're on Windows.362+For the *Script* input (**A**), navigate to your project's virtual environment.363+Within that folder, pick the ``flask`` executable which will reside in the364+``bin`` folder, or in the ``Scripts`` on Windows.365 319-The *Script Parameter* field (**B**) is set to the cli command you wish to320-execute, in this example we use ``run`` which will run our development server.366+The *Script Parameter* field (**B**) is set to the CLI command you to execute.367+In this example we use ``run``, which will run the development server.368 322-We need to add an environment variable (**C**) to identify our application.323-Click on the browse button and add an entry with ``FLASK_APP`` on the324-left and the name of the python file, or package on the right325-(``app.py`` for example).369+You can skip this next step if you're using :ref:`dotenv`. We need to add an370+environment variable (**C**) to identify our application. Click on the browse371+button and add an entry with ``FLASK_APP`` on the left and the name of the372+Python file or package on the right (``app.py`` for example).373 374 Next we need to set the working directory (**D**) to be the same folder where328-our application file or package resides.375+our application file or package resides. PyCharm changed it to the directory376+with the ``flask`` executable when we selected it earlier, which is incorrect.377 378 Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a331-good descriptive name, such as “Run Flask Server” and click *Apply*.379+good descriptive name, such as "Run Flask Server", and click *Apply*.380 333-Now that we have on run configuration which implements ``flask run`` from within334-PyCharm, we can simply copy that configuration and alter the script argument335-to run a different cli command, e.g. ``flask shell``.381+Now that we have a configuration which runs ``flask run`` from within PyCharm,382+we can simply copy that configuration and alter the *Script* argument383+to run a different CLI command, e.g. ``flask shell``.modified:docs/installation.rst+3 added
41 unmodified lines42 Python's ``json`` module. It is preferred for JSON operations if it is43 installed.44 * `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask``45 commands.46+* `Watchdog`_ provides a faster, more efficient reloader for the development47+ server.48 49 .. _Blinker: https://pythonhosted.org/blinker/50 .. _SimpleJSON: https://simplejson.readthedocs.io/51 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme52+.. _watchdog: https://pythonhosted.org/watchdog/53 54 Virtual environments55 --------------------56 125 unmodified linesmodified:flask/cli.py+22 added-20 removed
232 unmodified lines233 'python_version': sys.version,234 }, color=ctx.color)235 ctx.exit()236 237-version_option = click.Option(['--version'],238- help='Show the flask version',239- expose_value=False,240- callback=get_version,241- is_flag=True, is_eager=True)237 238+version_option = click.Option(239+ ['--version'],240+ help='Show the flask version',241+ expose_value=False,242+ callback=get_version,243+ is_flag=True,244+ is_eager=True245+)246+247+248 class DispatchingApp(object):249 """Special application that dispatches to a Flask application which250 is imported by name in a background thread. If an error happens251 it is recorded and shown as part of the WSGI handling which in case465 unmodified lines717 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())718 719 720 cli = FlaskGroup(help="""\716-This shell command acts as general utility script for Flask applications.721+A general utility script for Flask applications.722 718-It loads the application configured (through the FLASK_APP environment719-variable) and then provides commands either provided by the application or720-Flask itself.723+Provides commands from Flask, extensions, and the application. Loads the724+application defined in the FLASK_APP environment variable, or from a wsgi.py725+file. Debug mode can be controlled with the FLASK_DEBUG726+environment variable.727 722-The most useful commands are the "run" and "shell" command.723-724-Example usage:725-728 \b727- %(prefix)s%(cmd)s FLASK_APP=hello.py728- %(prefix)s%(cmd)s FLASK_DEBUG=1729- %(prefix)sflask run730-""" % {731- 'cmd': os.name == 'posix' and 'export' or 'set',732- 'prefix': os.name == 'posix' and '$ ' or '',733-})729+ {prefix}{cmd} FLASK_APP=hello.py730+ {prefix}{cmd} FLASK_DEBUG=1731+ {prefix}flask run732+""".format(733+ cmd='export' if os.name == 'posix' else 'set',734+ prefix='$ ' if os.name == 'posix' else '> '735+))736 737 738 def main(as_module=False):739 args = sys.argv[1:]20 unmodified lines