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
Provenance
- Commit
a7d829c- Tree
576737c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
523e271
10 files changed+112 added−141 removed
modified:docs/patterns/appfactories.rst+2 added-1 removed
97 unmodified lines98 app = create_app('/path/to/config.cfg')99 100 It can then be used with the :command:`flask` command::101 102- flask --app=exampleapp run102+ export FLASK_APP=exampleapp103+ flask run104 105 Factory Improvements106 --------------------107 9 unmodified linesmodified:docs/tutorial/dbcon.rst-1 removed
35 unmodified lines36 if not hasattr(g, 'sqlite_db'):37 g.sqlite_db = connect_db()38 return g.sqlite_db39 40-40 So now we know how to connect, but how do we properly disconnect? For41 that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`42 decorator. It's executed every time the application context tears down::43 34 unmodified linesmodified:docs/tutorial/dbinit.rst+1 added-1 removed
58 unmodified lines59 databases will not commit unless you explicitly tell it to.60 61 Now, it is possible to create a database with the :command:`flask` script::62 63- flask --app=flaskr initdb63+ flask initdb64 Initialized the database.65 66 .. admonition:: Troubleshooting67 5 unmodified linesmodified:docs/tutorial/setup.rst+8 added-5 removed
89 unmodified lines90 rv.row_factory = sqlite3.Row91 return rv92 93 With that out of the way, you should be able to start up the application94-without problems. Do this with the following command::94+without problems. Do this with the following commands::95 96- flask --app=flaskr --debug run96+ export FLASK_APP=flaskr97+ export FLASK_DEBUG=198+ flask run99 98-The :option:`--debug` flag enables or disables the interactive debugger. *Never99-leave debug mode activated in a production system*, because it will allow100-users to execute code on the server!100+(In case you are on Windows you need to use `set` instead of `export`).101+The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.102+*Never leave debug mode activated in a production system*, because it will103+allow users to execute code on the server!104 105 You will see a message telling you that server has started along with106 the address at which you can access it.107 11 unmodified linesmodified:docs/api.rst-7 removed
890 unmodified lines891 892 Marks a function so that an instance of :class:`ScriptInfo` is passed893 as first argument to the click callback.894 895-.. autofunction:: script_info_option896-897- 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.901-895 .. autodata:: run_command896 897 .. autodata:: shell_commandmodified:docs/cli.rst+49 added-92 removed
13 unmodified lines14 15 Basic Usage16 -----------17 18-After installation of Flask you will now find a :command:`flask` script installed19-into your virtualenv. If you don't want to install Flask or you have a20-special use-case you can also use ``python -m flask`` to accomplish exactly21-the same.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.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.27 28-For the :command:`flask` script to work, an application needs to be discovered.29-The two most common ways are either an environment variable30-(``FLASK_APP``) or the :option:`--app` / :option:`-a` parameter. It should be the31-import path for your application or the path to a Python file. In the32-latter case Flask will attempt to setup the Python path for you33-automatically and discover the module name but that might not always work.28+For the :command:`flask` script to work, an application needs to be29+discovered. This is achieved by exporting the ``FLASK_APP`` environment30+variable. It can be either set to an import path or to a filename of a31+Python module that contains a Flask application.32 33 In that imported file the name of the app needs to be called ``app`` or36-optionally be specified after a colon.34+optionally be specified after a colon. For instance35+`mymodule:application` would tell it to use the `application` object in36+the :file:`mymodule.py` file.37 38-Given a :file:`hello.py` file with the application in it named ``app`` this is39-how it can be run.38+Given a :file:`hello.py` file with the application in it named ``app``39+this is how it can be run.40 41 Environment variables (On Windows use ``set`` instead of ``export``)::42 43 export FLASK_APP=hello44 flask run45 46-Parameters::46+Or with a filename::47 48- flask --app=hello run48+ export FLASK_APP=/path/to/hello.py49+ flask run50 50-File names::51-52- flask --app=hello.py run53-51 Virtualenv Integration52 ----------------------53 54 If you are constantly working with a virtualenv you can also put the3 unmodified lines58 59 Debug Flag60 ----------61 65-The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` to66-automatically flip the debug flag of the application. This can also be67-configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.62+The :command:`flask` script can also be instructed to enable the debug63+mode of the application automatically by exporting ``FLASK_DEBUG``. If64+set to ``1`` debug is enabled or ``0`` disables it.65 66+Or with a filename::67+68+ export FLASK_DEBUG=169+70 Running a Shell71 ---------------72 73 To run an interactive Python shell you can use the ``shell`` command::74 74- flask --app=hello shell75+ flask shell76 77 This will start up an interactive Python shell, setup the correct78 application context and setup the local variables in the shell. This is79 done by invoking the :meth:`Flask.make_shell_context` method of the6 unmodified lines86 easily. Flask uses `click`_ for the command interface which makes87 creating custom commands very easy. For instance if you want a shell88 command to initialize the database you can do this::89 90+ import click91 from flask import Flask92 93 app = Flask(__name__)94 95 @app.cli.command()96 def initdb():97 """Initialize the database."""96- print 'Init the db'98+ click.echo('Init the db')99 100 The command will then show up on the command line::101 100- $ flask -a hello.py initdb102+ $ flask initdb103 Init the db104 105 Application Context106 -------------------16 unmodified lines123 Factory Functions124 -----------------125 126 In case you are using factory functions to create your application (see125-:ref:`app-factories`) you will discover that the :command:`flask` command cannot126-work with them directly. Flask won't be able to figure out how to127+:ref:`app-factories`) you will discover that the :command:`flask` command128+cannot work with them directly. Flask won't be able to figure out how to129 instantiate your application properly by itself. Because of this reason130 the recommendation is to create a separate file that instantiates129-applications. This is by far not the only way to make this work. Another130-is the :ref:`custom-scripts` support.131+applications. This is not the only way to make this work. Another is the132+:ref:`custom-scripts` support.133 134 For instance if you have a factory function that creates an application135 from a filename you could make a separate file that creates such an136 application from an environment variable.16 unmodified lines153 154 Custom Scripts155 --------------156 155-While the most common way is to use the :command:`flask` command, you can also156-make your own "driver scripts". Since Flask uses click for the scripts157-there is no reason you cannot hook these scripts into any click157+While the most common way is to use the :command:`flask` command, you can158+also make your own "driver scripts". Since Flask uses click for the159+scripts there is no reason you cannot hook these scripts into any click160 application. There is one big caveat and that is, that commands161 registered to :attr:`Flask.cli` will expect to be (indirectly at least)162 launched from a :class:`flask.cli.FlaskGroup` click group. This is163 necessary so that the commands know which Flask application they have to164 work with.165 166 To understand why you might want custom scripts you need to understand how165-click finds and executes the Flask application. If you use the :command:`flask`166-script you specify the application to work with on the command line or167-environment variable as an import name. This is simple but it has some168-limitations. Primarily it does not work with application factory169-functions (see :ref:`app-factories`).167+click finds and executes the Flask application. If you use the168+:command:`flask` script you specify the application to work with on the169+command line or environment variable as an import name. This is simple170+but it has some limitations. Primarily it does not work with application171+factory functions (see :ref:`app-factories`).172 173 With a custom script you don't have this problem as you can fully174 customize how the application will be created. This is very useful if you175 write reusable applications that you want to ship to users and they should176 be presented with a custom management script.177 176-If you are used to writing click applications this will look familiar but177-at the same time, slightly different because of how commands are loaded.178-We won't go into detail now about the differences but if you are curious179-you can have a look at the :ref:`script-info-object` section to learn all180-about it.181-178 To explain all of this, here is an example :file:`manage.py` script that179 manages a hypothetical wiki application. We will go through the details180 afterwards::181 182+ import os183 import click187- from flask.cli import FlaskGroup, script_info_option184+ from flask.cli import FlaskGroup185 186 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'))190 191 @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."""194 195 if __name__ == '__main__':196 cli()2 unmodified lines199 step.200 201 1. 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.204 2. 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`).214-215- 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.210 3. 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.213 214 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.224-4. 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.229-5. All is rounded up by invoking the script.216+4. All is rounded up by invoking the script.230-231-.. _script-info-object:232-233-The Script Info234----------------235-236-The Flask script integration might be confusing at first, but there is a reason237-why it's done this way. The reason for this is that Flask wants to238-both provide custom commands to click as well as not loading your239-application unless it has to. The reason for this is added flexibility.240-241-This way an application can provide custom commands, but even in the242-absence of an application the :command:`flask` script is still operational on a243-basic level. In addition to that it means that the individual commands244-have the option to avoid creating an instance of the Flask application245-unless required. This is very useful as it allows the server commands for246-instance to load the application on a first request instead of247-immediately, therefore giving a better debug experience.248-249-All of this is provided through the :class:`flask.cli.ScriptInfo` object250-and some helper utilities around. The basic way it operates is that when251-the :class:`flask.cli.FlaskGroup` executes as a script it creates a script252-info and keeps it around. From that point onwards modifications on the253-script info can be done through click options. To simplify this pattern254-the :func:`flask.cli.script_info_option` decorator was added.255-256-Once Flask actually needs the individual Flask application it will invoke257-the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the258-server starts, when the shell is launched or when the script looks for an259-application-provided click command.modified:docs/quickstart.rst+22 added-22 removed
40 unmodified lines41 interpreter. Make sure to not call your application :file:`flask.py` because this42 would conflict with Flask itself.43 44 To run the application you can either use the :command:`flask` command or45-python's :option:`-m` switch with Flask::45+python's :option:`-m` switch with Flask. Before you can do that you need46+to tell your terminal the application to work with by exporting the47+`FLASK_APP` environment variable::48 49+ $ export FLASK_APP=hello.py47- $ flask -a hello run50+ $ flask run51 * Running on http://127.0.0.1:5000/52 50-or alternatively::53+If you are on Windows you need to use `set` instead of `export`.54 55+Alternatively you can use `python -m flask`::56+57+ $ export FLASK_APP=hello.py52- $ python -m flask -a hello run58+ $ python -m flask run59 * Running on http://127.0.0.1:5000/60 61 This launches a very simple builtin server, which is good enough for testing62 but probably not what you want to use in production. For deployment options see14 unmodified lines77 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::80 75- flask -a hello run --host=0.0.0.081+ flask run --host=0.0.0.082 83 This tells your operating system to listen on all public IPs.84 85 6 unmodified lines92 93 Old Version of Flask94 ````````````````````95 90-Versions of Flask older than 1.0 use to have different ways to start the96+Versions of Flask older than 0.11 use to have different ways to start the97 application. In short, the :command:`flask` command did not exist, and98 neither did ``python -m flask``. In that case you have two options:99 either upgrade to newer Flask versions or have a look at the :ref:`server`100 docs to see the alternative method for running a server.101 96-Python older 2.797-````````````````98-99-In case you have a version of Python older than 2.7 ``python -m flask``100-does not work. You can either use :command:`flask` or ``python -m101-flask.cli`` as an alternative. This is because Python before 2.7 does no102-permit packages to act as executable modules. For more information see103-:ref:`cli`.104-102 Invalid Import Name103 ```````````````````104 108-The :option:`-a` argument to :command:`flask` is the name of the module to import. In109-case that module is incorrectly named you will get an import error upon110-start (or if debug is enabled when you navigate to the application). It111-will tell you what it tried to import and why it failed.105+The :option:`-a` argument to :command:`flask` is the name of the module to106+import. In case that module is incorrectly named you will get an import107+error upon start (or if debug is enabled when you navigate to the108+application). It will tell you what it tried to import and why it failed.109 110 The most common reason is a typo or because you did not actually create an111 ``app`` object.112 9 unmodified lines122 That is not very nice and Flask can do better. If you enable debug123 support the server will reload itself on code changes, and it will also124 provide you with a helpful debugger if things go wrong.125 129-There are different ways to enable the debug mode. The most obvious one130-is the :option:`--debug` parameter to the :command:`flask` command::126+To enable debug mode you can export the `FLASK_DEBUG` environment variable127+before running the server::128 132- flask --debug -a hello run129+ $ export FLASK_DEBUG=1130+ $ flask run131 132+(On Windows you need to use `set` instead of `export`).133+134 This does the following things:135 136 1. it activates the debugger137 2. it activates the automatic reloader757 unmodified linesmodified:examples/flaskr/README+8 added-4 removed
11 unmodified lines12 1. edit the configuration in the flaskr.py file or13 export an FLASKR_SETTINGS environment variable14 pointing to a configuration file.15 16- 2. initialize the database with this command:16+ 2. Instruct flask to use the right application17 18- flask --app=flaskr initdb18+ export FLASK_APP=flaskr19 20- 3. now you can run flaskr:20+ 3. initialize the database with this command:21 22- flask --app=flaskr run22+ flask initdb23 24+ 4. now you can run flaskr:25+26+ flask run27+28 the application will greet you on29 http://localhost:5000/30 31 ~ Is it tested?3 unmodified linesmodified:examples/minitwit/README+6 added-2 removed
12 unmodified lines13 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.16 17+ 2. tell flask about the right application:18+19+ export FLASK_APP=minitwit20+21 2. fire up a shell and run this:22 19- flask --app=minitwit initdb23+ flask initdb24 25 3. now you can run minitwit:26 23- flask --app=minitwit run27+ flask run28 29 the application will greet you on30 http://localhost:5000/31 4 unmodified linesmodified:flask/cli.py+16 added-6 removed
163 unmodified lines164 165 class 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 """173 174 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 = None181+182+ #: 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 with11 unmodified lines199 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 = debug163 unmodified lines376 # 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'))382 383 run_simple(host, port, app, use_reloader=reload,384 use_debugger=debugger, threaded=with_threads)385 78 unmodified lines