Skip to content
Myr

Update docs to the new CLI patterns

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 523e271 · Browse files · 10 files+112 added−141 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+112 added−141 removed

  • other:+112 added−141 removed

10 files+112 added−141 removed

modified:docs/patterns/appfactories.rst+2 added-1 removed
97 unmodified lines
98 app = create_app('/path/to/config.cfg')99100It can then be used with the :command:`flask` command::101102 flask --app=exampleapp run102 export FLASK_APP=exampleapp103 flask run104105Factory Improvements106--------------------107
9 unmodified lines
modified:docs/tutorial/dbcon.rst-1 removed
35 unmodified lines
36 if not hasattr(g, 'sqlite_db'):37 g.sqlite_db = connect_db()38 return g.sqlite_db394040So now we know how to connect, but how do we properly disconnect? For41that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`42decorator. It's executed every time the application context tears down::43
34 unmodified lines
modified:docs/tutorial/dbinit.rst+1 added-1 removed
58 unmodified lines
59databases will not commit unless you explicitly tell it to.6061Now, it is possible to create a database with the :command:`flask` script::6263 flask --app=flaskr initdb63 flask initdb64 Initialized the database.6566.. admonition:: Troubleshooting67
5 unmodified lines
modified:docs/tutorial/setup.rst+8 added-5 removed
89 unmodified lines
90 rv.row_factory = sqlite3.Row91 return rv9293With that out of the way, you should be able to start up the application94without problems. Do this with the following command::94without problems. Do this with the following commands::9596 flask --app=flaskr --debug run96 export FLASK_APP=flaskr97 export FLASK_DEBUG=198 flask run9998The :option:`--debug` flag enables or disables the interactive debugger. *Never99leave debug mode activated in a production system*, because it will allow100users to execute code on the server!100(In case you are on Windows you need to use `set` instead of `export`).101The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.102*Never leave debug mode activated in a production system*, because it will103allow users to execute code on the server!104105You will see a message telling you that server has started along with106the address at which you can access it.107
11 unmodified lines
modified:docs/api.rst-7 removed
890 unmodified lines
891892 Marks a function so that an instance of :class:`ScriptInfo` is passed893 as first argument to the click callback.894895.. autofunction:: script_info_option896897 A special decorator that informs a click callback to be passed the898 script info object as first argument. This is normally not useful899 unless you implement very special commands like the run command which900 does not want the application to be loaded yet.901895.. autodata:: run_command896897.. autodata:: shell_command
modified:docs/cli.rst+49 added-92 removed
13 unmodified lines
1415Basic Usage16-----------1718After installation of Flask you will now find a :command:`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.18After 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.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 :command:`flask` script to work, an application needs to be discovered.29The two most common ways are either an environment variable30(``FLASK_APP``) or the :option:`--app` / :option:`-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.28For the :command:`flask` script to work, an application needs to be29discovered. This is achieved by exporting the ``FLASK_APP`` environment30variable. It can be either set to an import path or to a filename of a31Python module that contains a Flask application.3233In that imported file the name of the app needs to be called ``app`` or36optionally be specified after a colon.34optionally be specified after a colon. For instance35`mymodule:application` would tell it to use the `application` object in36the :file:`mymodule.py` file.3738Given a :file:`hello.py` file with the application in it named ``app`` this is39how it can be run.38Given a :file:`hello.py` file with the application in it named ``app``39this is how it can be run.4041Environment variables (On Windows use ``set`` instead of ``export``)::4243 export FLASK_APP=hello44 flask run4546Parameters::46Or with a filename::4748 flask --app=hello run48 export FLASK_APP=/path/to/hello.py49 flask run5050File names::5152 flask --app=hello.py run5351Virtualenv Integration52----------------------5354If you are constantly working with a virtualenv you can also put the
3 unmodified lines
5859Debug Flag60----------6165The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` to66automatically flip the debug flag of the application. This can also be67configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.62The :command:`flask` script can also be instructed to enable the debug63mode of the application automatically by exporting ``FLASK_DEBUG``. If64set to ``1`` debug is enabled or ``0`` disables it.6566Or with a filename::6768 export FLASK_DEBUG=16970Running a Shell71---------------7273To run an interactive Python shell you can use the ``shell`` command::7474 flask --app=hello shell75 flask shell7677This will start up an interactive Python shell, setup the correct78application context and setup the local variables in the shell. This is79done by invoking the :meth:`Flask.make_shell_context` method of the
6 unmodified lines
86easily. Flask uses `click`_ for the command interface which makes87creating custom commands very easy. For instance if you want a shell88command to initialize the database you can do this::8990 import click91 from flask import Flask9293 app = Flask(__name__)9495 @app.cli.command()96 def initdb():97 """Initialize the database."""96 print 'Init the db'98 click.echo('Init the db')99100The command will then show up on the command line::101100 $ flask -a hello.py initdb102 $ flask initdb103 Init the db104105Application Context106-------------------
16 unmodified lines
123Factory Functions124-----------------125126In case you are using factory functions to create your application (see125:ref:`app-factories`) you will discover that the :command:`flask` command cannot126work with them directly. Flask won't be able to figure out how to127:ref:`app-factories`) you will discover that the :command:`flask` command128cannot work with them directly. Flask won't be able to figure out how to129instantiate your application properly by itself. Because of this reason130the recommendation is to create a separate file that instantiates129applications. This is by far not the only way to make this work. Another130is the :ref:`custom-scripts` support.131applications. This is not the only way to make this work. Another is the132:ref:`custom-scripts` support.133134For instance if you have a factory function that creates an application135from a filename you could make a separate file that creates such an136application from an environment variable.
16 unmodified lines
153154Custom Scripts155--------------156155While the most common way is to use the :command:`flask` command, you can also156make your own "driver scripts". Since Flask uses click for the scripts157there is no reason you cannot hook these scripts into any click157While the most common way is to use the :command:`flask` command, you can158also make your own "driver scripts". Since Flask uses click for the159scripts there is no reason you cannot hook these scripts into any click160application. There is one big caveat and that is, that commands161registered to :attr:`Flask.cli` will expect to be (indirectly at least)162launched from a :class:`flask.cli.FlaskGroup` click group. This is163necessary so that the commands know which Flask application they have to164work with.165166To understand why you might want custom scripts you need to understand how165click finds and executes the Flask application. If you use the :command:`flask`166script you specify the application to work with on the command line or167environment variable as an import name. This is simple but it has some168limitations. Primarily it does not work with application factory169functions (see :ref:`app-factories`).167click finds and executes the Flask application. If you use the168:command:`flask` script you specify the application to work with on the169command line or environment variable as an import name. This is simple170but it has some limitations. Primarily it does not work with application171factory functions (see :ref:`app-factories`).172173With a custom script you don't have this problem as you can fully174customize how the application will be created. This is very useful if you175write reusable applications that you want to ship to users and they should176be presented with a custom management script.177176If you are used to writing click applications this will look familiar but177at the same time, slightly different because of how commands are loaded.178We won't go into detail now about the differences but if you are curious179you can have a look at the :ref:`script-info-object` section to learn all180about it.181178To explain all of this, here is an example :file:`manage.py` script that179manages a hypothetical wiki application. We will go through the details180afterwards::181182 import os183 import click187 from flask.cli import FlaskGroup, script_info_option184 from flask.cli import FlaskGroup185186 def create_wiki_app(info):187 from yourwiki import create_app191 config = info.data.get('config') or 'wikiconfig.py'192 return create_app(config=config)188 return create_app(189 config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))190191 @click.group(cls=FlaskGroup, create_app=create_wiki_app)195 @script_info_option('--config', script_info_key='config')196 def cli(**params):192 def cli():193 """This is a management script for the wiki application."""194195 if __name__ == '__main__':196 cli()
2 unmodified lines
199step.2002011. First we import the ``click`` library as well as the click extensions202 from the ``flask.cli`` package. Primarily we are here interested207 in the :class:`~flask.cli.FlaskGroup` click group and the208 :func:`~flask.cli.script_info_option` decorator.203 in the :class:`~flask.cli.FlaskGroup` click group.2042. The next thing we do is defining a function that is invoked with the210 script info object (:ref:`script-info-object`) from Flask and its205 script info object (:class:`~flask.cli.ScriptInfo`) from Flask and its206 purpose is to fully import and create the application. This can207 either directly import an application object or create it (see213 :ref:`app-factories`).214215 What is ``info.data``? It's a dictionary of arbitrary data on the216 script info that can be filled by options or through other means. We217 will come back to this later.208 :ref:`app-factories`). In this case we load the config from an209 environment variable.2103. Next step is to create a :class:`FlaskGroup`. In this case we just211 make an empty function with a help doc string that just does nothing212 and then pass the ``create_wiki_app`` function as a factory function.213214 Whenever click now needs to operate on a Flask application it will215 call that function with the script info and ask for it to be created.2244. In step 2 you could see that the config is passed to the actual225 creation function. This config comes from the :func:`script_info_option`226 decorator for the main script. It accepts a :option:`--config` option and227 then stores it in the script info so we can use it to create the228 application.2295. All is rounded up by invoking the script.2164. All is rounded up by invoking the script.230231.. _script-info-object:232233The Script Info234---------------235236The Flask script integration might be confusing at first, but there is a reason237why it's done this way. The reason for this is that Flask wants to238both provide custom commands to click as well as not loading your239application unless it has to. The reason for this is added flexibility.240241This way an application can provide custom commands, but even in the242absence of an application the :command:`flask` script is still operational on a243basic level. In addition to that it means that the individual commands244have the option to avoid creating an instance of the Flask application245unless required. This is very useful as it allows the server commands for246instance to load the application on a first request instead of247immediately, therefore giving a better debug experience.248249All of this is provided through the :class:`flask.cli.ScriptInfo` object250and some helper utilities around. The basic way it operates is that when251the :class:`flask.cli.FlaskGroup` executes as a script it creates a script252info and keeps it around. From that point onwards modifications on the253script info can be done through click options. To simplify this pattern254the :func:`flask.cli.script_info_option` decorator was added.255256Once Flask actually needs the individual Flask application it will invoke257the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the258server starts, when the shell is launched or when the script looks for an259application-provided click command.
modified:docs/quickstart.rst+22 added-22 removed
40 unmodified lines
41interpreter. Make sure to not call your application :file:`flask.py` because this42would conflict with Flask itself.4344To run the application you can either use the :command:`flask` command or45python's :option:`-m` switch with Flask::45python's :option:`-m` switch with Flask. Before you can do that you need46to tell your terminal the application to work with by exporting the47`FLASK_APP` environment variable::4849 $ export FLASK_APP=hello.py47 $ flask -a hello run50 $ flask run51 * Running on http://127.0.0.1:5000/5250or alternatively::53If you are on Windows you need to use `set` instead of `export`.5455Alternatively you can use `python -m flask`::5657 $ export FLASK_APP=hello.py52 $ python -m flask -a hello run58 $ python -m flask run59 * Running on http://127.0.0.1:5000/6061This launches a very simple builtin server, which is good enough for testing62but probably not what you want to use in production. For deployment options see
14 unmodified lines
77 If you have the debugger disabled or trust the users on your network,78 you can make the server publicly available simply by adding79 ``--host=0.0.0.0`` to the command line::8075 flask -a hello run --host=0.0.0.081 flask run --host=0.0.0.08283 This tells your operating system to listen on all public IPs.8485
6 unmodified lines
9293Old Version of Flask94````````````````````9590Versions of Flask older than 1.0 use to have different ways to start the96Versions of Flask older than 0.11 use to have different ways to start the97application. In short, the :command:`flask` command did not exist, and98neither did ``python -m flask``. In that case you have two options:99either upgrade to newer Flask versions or have a look at the :ref:`server`100docs to see the alternative method for running a server.10196Python older 2.797````````````````9899In case you have a version of Python older than 2.7 ``python -m flask``100does not work. You can either use :command:`flask` or ``python -m101flask.cli`` as an alternative. This is because Python before 2.7 does no102permit packages to act as executable modules. For more information see103:ref:`cli`.104102Invalid Import Name103```````````````````104108The :option:`-a` argument to :command:`flask` is the name of the module to import. In109case that module is incorrectly named you will get an import error upon110start (or if debug is enabled when you navigate to the application). It111will tell you what it tried to import and why it failed.105The :option:`-a` argument to :command:`flask` is the name of the module to106import. In case that module is incorrectly named you will get an import107error upon start (or if debug is enabled when you navigate to the108application). It will tell you what it tried to import and why it failed.109110The most common reason is a typo or because you did not actually create an111``app`` object.112
9 unmodified lines
122That is not very nice and Flask can do better. If you enable debug123support the server will reload itself on code changes, and it will also124provide you with a helpful debugger if things go wrong.125129There are different ways to enable the debug mode. The most obvious one130is the :option:`--debug` parameter to the :command:`flask` command::126To enable debug mode you can export the `FLASK_DEBUG` environment variable127before running the server::128132 flask --debug -a hello run129 $ export FLASK_DEBUG=1130 $ flask run131132(On Windows you need to use `set` instead of `export`).133134This does the following things:1351361. it activates the debugger1372. it activates the automatic reloader
757 unmodified lines
modified:examples/flaskr/README+8 added-4 removed
11 unmodified lines
12 1. edit the configuration in the flaskr.py file or13 export an FLASKR_SETTINGS environment variable14 pointing to a configuration file.1516 2. initialize the database with this command:16 2. Instruct flask to use the right application1718 flask --app=flaskr initdb18 export FLASK_APP=flaskr1920 3. now you can run flaskr:20 3. initialize the database with this command:2122 flask --app=flaskr run22 flask initdb2324 4. now you can run flaskr:2526 flask run2728 the application will greet you on29 http://localhost:5000/3031 ~ Is it tested?
3 unmodified lines
modified:examples/minitwit/README+6 added-2 removed
12 unmodified lines
13 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.1617 2. tell flask about the right application:1819 export FLASK_APP=minitwit2021 2. fire up a shell and run this:2219 flask --app=minitwit initdb23 flask initdb2425 3. now you can run minitwit:2623 flask --app=minitwit run27 flask run2829 the application will greet you on30 http://localhost:5000/31
4 unmodified lines
modified:flask/cli.py+16 added-6 removed
163 unmodified lines
164165class ScriptInfo(object):166 """Help object to deal with Flask applications. This is usually not167 necessary to interface with as it's used internally in the dispatching168 to click.168 to click. In future versions of Flask this object will most likely play169 a bigger role. Typically it's created automatically by the170 :class:`FlaskGroup` but you can also manually create it and pass it171 onwards as click object.172 """173174 def __init__(self, app_import_path=None, create_app=None):175 if create_app is None:176 if app_import_path is None:177 app_import_path = find_default_import_path()178 self.app_import_path = app_import_path179 else:177 self.app_import_path = None180 app_import_path = None181182 #: Optionally the import path for the Flask application.183 self.app_import_path = app_import_path184 #: Optionally a function that is passed the script info to create185 #: the instance of the application.186 self.create_app = create_app187 #: A dictionary with arbitrary data that can be associated with
11 unmodified lines
199 return self._loaded_app200 if self.create_app is not None:201 rv = self.create_app(self)202 else:197 if self.app_import_path is None:198 raise NoAppException('Could not locate Flask application. '199 'You did not provide the FLASK_APP '200 'environment variable.')203 if not self.app_import_path:204 raise NoAppException(205 'Could not locate Flask application. You did not provide '206 'the FLASK_APP environment variable.\n\nFor more '207 'information see '208 'http://flask.pocoo.org/docs/latest/quickstart/')209 rv = locate_app(self.app_import_path)210 debug = get_debug_flag()211 if debug is not None:212 rv.debug = debug
163 unmodified lines
376 # import path because the app was loaded through a callback then377 # we won't print anything.378 if info.app_import_path is not None:379 print(' * Serving Flask app "%s"' % info.app_import_path)380 if debug is not None:381 print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))382383 run_simple(host, port, app, use_reloader=reload,384 use_debugger=debugger, threaded=with_threads)385
78 unmodified lines