Merge pull request #4646 from pallets/cli-app-env
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents fe4003b, ab1fbef · Browse files · 18 files·+343 added−633 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+343 added−633 removed
- tests:+1 added−0 removed
- other:+342 added−633 removed
Provenance
- Commit
ae54727- Tree
ada1b87- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
fe4003b- Parent 2
ab1fbef
18 files changed+343 added−633 removed
modified:docs/patterns/appfactories.rst+9 added-60 removed
87 unmodified lines88 ------------------89 90 To run such an application, you can use the :command:`flask` command:91 92-.. tabs::92+.. code-block:: text93 94- .. group-tab:: Bash94+ $ flask run --app hello run95 96- .. code-block:: text96+Flask will automatically detect the factory if it is named97+``create_app`` or ``make_app`` in ``hello``. You can also pass arguments98+to the factory like this:99 98- $ export FLASK_APP=myapp99- $ flask run100+.. code-block:: text101 101- .. group-tab:: Fish102+ $ flask run --app hello:create_app(local_auth=True)``103 103- .. code-block:: text104+Then the ``create_app`` factory in ``myapp`` is called with the keyword105+argument ``local_auth=True``. See :doc:`/cli` for more detail.106 105- $ set -x FLASK_APP myapp106- $ flask run107-108- .. group-tab:: CMD109-110- .. code-block:: text111-112- > set FLASK_APP=myapp113- > flask run114-115- .. group-tab:: Powershell116-117- .. code-block:: text118-119- > $env:FLASK_APP = "myapp"120- > flask run121-122-Flask will automatically detect the factory (``create_app`` or ``make_app``)123-in ``myapp``. You can also pass arguments to the factory like this:124-125-.. tabs::126-127- .. group-tab:: Bash128-129- .. code-block:: text130-131- $ export FLASK_APP="myapp:create_app('dev')"132- $ flask run133-134- .. group-tab:: Fish135-136- .. code-block:: text137-138- $ set -x FLASK_APP "myapp:create_app('dev')"139- $ flask run140-141- .. group-tab:: CMD142-143- .. code-block:: text144-145- > set FLASK_APP="myapp:create_app('dev')"146- > flask run147-148- .. group-tab:: Powershell149-150- .. code-block:: text151-152- > $env:FLASK_APP = "myapp:create_app('dev')"153- > flask run154-155-Then the ``create_app`` factory in ``myapp`` is called with the string156-``'dev'`` as the argument. See :doc:`/cli` for more detail.157-107 Factory Improvements108 --------------------109 110 The factory function above is not very clever, but you can improve it.8 unmodified linesmodified:docs/patterns/packages.rst+7 added-60 removed
54 unmodified lines55 'flask',56 ],57 )58 59-In order to run the application you need to export an environment variable60-that tells Flask where to find the application instance:59+Install your application so it is importable:60 62-.. tabs::61+.. code-block:: text62 64- .. group-tab:: Bash63+ $ pip install -e .64 66- .. code-block:: text65+To use the ``flask`` command and run your application you need to set66+the ``--app`` option that tells Flask where to find the application67+instance:68 68- $ export FLASK_APP=yourapplication69+ $ flask --app yourapplication run70 70- .. group-tab:: Fish71-72- .. code-block:: text73-74- $ set -x FLASK_APP yourapplication75-76- .. group-tab:: CMD77-78- .. code-block:: text79-80- > set FLASK_APP=yourapplication81-82- .. group-tab:: Powershell83-84- .. code-block:: text85-86- > $env:FLASK_APP = "yourapplication"87-88-If you are outside of the project directory make sure to provide the exact89-path to your application directory. Similarly you can turn on the90-development features like this:91-92-.. tabs::93-94- .. group-tab:: Bash95-96- .. code-block:: text97-98- $ export FLASK_ENV=development99-100- .. group-tab:: Fish101-102- .. code-block:: text103-104- $ set -x FLASK_ENV development105-106- .. group-tab:: CMD107-108- .. code-block:: text109-110- > set FLASK_ENV=development111-112- .. group-tab:: Powershell113-114- .. code-block:: text115-116- > $env:FLASK_ENV = "development"117-118-In order to install and run the application you need to issue the following119-commands::120-121- $ pip install -e .122- $ flask run123-71 What did we gain from this? Now we can restructure the application a bit72 into multiple modules. The only thing you have to remember is the73 following quick checklist:74 56 unmodified linesmodified:docs/tutorial/database.rst+2 added-4 removed
194 unmodified lines195 196 If you're still running the server from the previous page, you can197 either stop the server, or run this command in a new terminal. If198 you use a new terminal, remember to change to your project directory199- and activate the env as described in :doc:`/installation`. You'll200- also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on the201- previous page.199+ and activate the env as described in :doc:`/installation`.200 201 Run the ``init-db`` command:202 203 .. code-block:: none204 207- $ flask init-db205+ $ flask --app flaskr init-db206 Initialized the database.207 208 There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in209 your project.2 unmodified linesmodified:docs/tutorial/deploy.rst+3 added-29 removed
46 unmodified lines47 48 Since this is a different machine, you need to run ``init-db`` again to49 create the database in the instance folder.50 51-.. tabs::51+ .. code-block:: text52 53- .. group-tab:: Bash53+ $ flask --app flaskr init-db54 55- .. code-block:: text56-57- $ export FLASK_APP=flaskr58- $ flask init-db59-60- .. group-tab:: Fish61-62- .. code-block:: text63-64- $ set -x FLASK_APP flaskr65- $ flask init-db66-67- .. group-tab:: CMD68-69- .. code-block:: text70-71- > set FLASK_APP=flaskr72- > flask init-db73-74- .. group-tab:: Powershell75-76- .. code-block:: text77-78- > $env:FLASK_APP = "flaskr"79- > flask init-db80-55 When Flask detects that it's installed (not in editable mode), it uses56 a different directory for the instance folder. You can find it at57 ``venv/var/flaskr-instance`` instead.58 41 unmodified lines100 101 $ pip install waitress102 103 You need to tell Waitress about your application, but it doesn't use130-``FLASK_APP`` like ``flask run`` does. You need to tell it to import and104+``--app`` like ``flask run`` does. You need to tell it to import and105 call the application factory to get an application object.106 107 .. code-block:: none108 12 unmodified linesmodified:docs/tutorial/factory.rst+4 added-34 removed
133 unmodified lines134 exception, and restarts the server whenever you make changes to the135 code. You can leave it running and just reload the browser page as you136 follow the tutorial.137 138-.. tabs::138+.. code-block:: text139 140- .. group-tab:: Bash140+ $ flask --app flaskr --env development run141 142- .. code-block:: text143-144- $ export FLASK_APP=flaskr145- $ export FLASK_ENV=development146- $ flask run147-148- .. group-tab:: Fish149-150- .. code-block:: text151-152- $ set -x FLASK_APP flaskr153- $ set -x FLASK_ENV development154- $ flask run155-156- .. group-tab:: CMD157-158- .. code-block:: text159-160- > set FLASK_APP=flaskr161- > set FLASK_ENV=development162- > flask run163-164- .. group-tab:: Powershell165-166- .. code-block:: text167-168- > $env:FLASK_APP = "flaskr"169- > $env:FLASK_ENV = "development"170- > flask run171-142 You'll see output similar to this:143 174-.. code-block:: none144+.. code-block:: text145 146 * Serving Flask app "flaskr"147 * Environment: development148 * Debug mode: on149 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)150 * Restarting with stat151 * Debugger is active!182- * Debugger PIN: 855-212-761152+ * Debugger PIN: nnn-nnn-nnn153 154 Visit http://127.0.0.1:5000/hello in a browser and you should see the155 "Hello, World!" message. Congratulations, you're now running your Flask156 web application!7 unmodified linesmodified:docs/tutorial/install.rst+1 added-1 removed
107 unmodified lines108 Werkzeug 0.14.1109 wheel 0.30.0110 111 Nothing changes from how you've been running your project so far.112-``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs112+``--app`` is still set to ``flaskr`` and ``flask run`` still runs113 the application, but you can call it from anywhere, not just the114 ``flask-tutorial`` directory.115 116 Continue to :doc:`tests`.modified:docs/cli.rst+48 added-158 removed
13 unmodified lines14 Application Discovery15 ---------------------16 17 The ``flask`` command is installed by Flask, not your application; it must be18-told where to find your application in order to use it. The ``FLASK_APP``19-environment variable is used to specify how to load the application.18+told where to find your application in order to use it. The ``--app``19+option is used to specify how to load the application.20 21-.. tabs::22-23- .. group-tab:: Bash24-25- .. code-block:: text26-27- $ export FLASK_APP=hello28- $ flask run29-30- .. group-tab:: Fish31-32- .. code-block:: text33-34- $ set -x FLASK_APP hello35- $ flask run36-37- .. group-tab:: CMD38-39- .. code-block:: text40-41- > set FLASK_APP=hello42- > flask run43-44- .. group-tab:: Powershell45-46- .. code-block:: text47-48- > $env:FLASK_APP = "hello"49- > flask run50-51-While ``FLASK_APP`` supports a variety of options for specifying your21+While ``--app`` supports a variety of options for specifying your22 application, most use cases should be simple. Here are the typical values:23 24 (nothing)25 The name "app" or "wsgi" is imported (as a ".py" file, or package),26 automatically detecting an app (``app`` or ``application``) or27 factory (``create_app`` or ``make_app``).28 59-``FLASK_APP=hello``29+``--app hello``30 The given name is imported, automatically detecting an app (``app``31 or ``application``) or factory (``create_app`` or ``make_app``).32 33 ----34 65-``FLASK_APP`` has three parts: an optional path that sets the current working35+``--app`` has three parts: an optional path that sets the current working36 directory, a Python file or dotted import path, and an optional variable37 name of the instance or factory. If the name is a factory, it can optionally38 be followed by arguments in parentheses. The following values demonstrate these39 parts:40 71-``FLASK_APP=src/hello``41+``--app src/hello``42 Sets the current working directory to ``src`` then imports ``hello``.43 74-``FLASK_APP=hello.web``44+``--app hello.web``45 Imports the path ``hello.web``.46 77-``FLASK_APP=hello:app2``47+``--app hello:app2``48 Uses the ``app2`` Flask instance in ``hello``.49 80-``FLASK_APP="hello:create_app('dev')"``50+``--app 'hello:create_app("dev")'``51 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``52 as the argument.53 84-If ``FLASK_APP`` is not set, the command will try to import "app" or54+If ``--app`` is not set, the command will try to import "app" or55 "wsgi" (as a ".py" file, or package) and try to detect an application56 instance or factory.57 58 Within the given import, the command looks for an application instance named47 unmodified lines106 ------------107 108 .. versionadded:: 1.0109 140-The environment in which the Flask app runs is set by the141-:envvar:`FLASK_ENV` environment variable. If not set it defaults to110+The environment in which the Flask app executes is set by the111+``FLASK_ENV`` environment variable. When using the ``flask`` command, it112+can also be set with the ``--env`` option. If not set it defaults to113 ``production``. The other recognized environment is ``development``.114 Flask and extensions may choose to enable behaviors based on the115 environment.116 117 If the env is set to ``development``, the ``flask`` command will enable118 debug mode and ``flask run`` will enable the interactive debugger and119 reloader.120 150-.. tabs::121+.. code-block:: text122 152- .. group-tab:: Bash123+ $ flask --app hello --env development run124+ * Serving Flask app "hello"125+ * Environment: development126+ * Debug mode: on127+ * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)128+ * Restarting with inotify reloader129+ * Debugger is active!130+ * Debugger PIN: 223-456-919131 154- .. code-block:: text132 156- $ export FLASK_ENV=development157- $ flask run158- * Serving Flask app "hello"159- * Environment: development160- * Debug mode: on161- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)162- * Restarting with inotify reloader163- * Debugger is active!164- * Debugger PIN: 223-456-919165-166- .. group-tab:: Fish167-168- .. code-block:: text169-170- $ set -x FLASK_ENV development171- $ flask run172- * Serving Flask app "hello"173- * Environment: development174- * Debug mode: on175- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)176- * Restarting with inotify reloader177- * Debugger is active!178- * Debugger PIN: 223-456-919179-180- .. group-tab:: CMD181-182- .. code-block:: text183-184- > set FLASK_ENV=development185- > flask run186- * Serving Flask app "hello"187- * Environment: development188- * Debug mode: on189- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)190- * Restarting with inotify reloader191- * Debugger is active!192- * Debugger PIN: 223-456-919193-194- .. group-tab:: Powershell195-196- .. code-block:: text197-198- > $env:FLASK_ENV = "development"199- > flask run200- * Serving Flask app "hello"201- * Environment: development202- * Debug mode: on203- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)204- * Restarting with inotify reloader205- * Debugger is active!206- * Debugger PIN: 223-456-919207-208-133 Watch Extra Files with the Reloader134 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~135 136 When using development mode, the reloader will trigger whenever your137 Python code or imported modules change. The reloader can watch214-additional files with the ``--extra-files`` option, or the215-``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are138+additional files with the ``--extra-files`` option. Multiple paths are139 separated with ``:``, or ``;`` on Windows.140 218-.. tabs::141+.. code-block:: text142 220- .. group-tab:: Bash143+ $ flask run --extra-files file1:dirA/file2:dirB/144+ * Running on http://127.0.0.1:8000/145+ * Detected change in '/path/to/file1', reloading146 222- .. code-block:: text147 224- $ flask run --extra-files file1:dirA/file2:dirB/225- # or226- $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/227- $ flask run228- * Running on http://127.0.0.1:8000/229- * Detected change in '/path/to/file1', reloading230-231- .. group-tab:: Fish232-233- .. code-block:: text234-235- $ flask run --extra-files file1:dirA/file2:dirB/236- # or237- $ set -x FLASK_RUN_EXTRA_FILES file1 dirA/file2 dirB/238- $ flask run239- * Running on http://127.0.0.1:8000/240- * Detected change in '/path/to/file1', reloading241-242- .. group-tab:: CMD243-244- .. code-block:: text245-246- > flask run --extra-files file1:dirA/file2:dirB/247- # or248- > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/249- > flask run250- * Running on http://127.0.0.1:8000/251- * Detected change in '/path/to/file1', reloading252-253- .. group-tab:: Powershell254-255- .. code-block:: text256-257- > flask run --extra-files file1:dirA/file2:dirB/258- # or259- > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"260- > flask run261- * Running on http://127.0.0.1:8000/262- * Detected change in '/path/to/file1', reloading263-264-148 Ignore files with the Reloader149 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~150 151 The reloader can also ignore files using :mod:`fnmatch` patterns with269-the ``--exclude-patterns`` option, or the ``FLASK_RUN_EXCLUDE_PATTERNS``270-environment variable. Multiple patterns are separated with ``:``, or271-``;`` on Windows.152+the ``--exclude-patterns`` option. Multiple patterns are separated with153+``:``, or ``;`` on Windows.154 155 156 Debug Mode157 ----------158 277-Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,278-as described above. If you want to control debug mode separately, use279-:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.159+Debug mode will be enabled when the execution environment is160+``development``, as described above. If you want to control debug mode161+separately, use the ``--debug/--no-debug`` option or the ``FLASK_DEBUG``162+environment variable.163 164 165 .. _dotenv:166 167 Environment Variables From dotenv168 ---------------------------------169 287-Rather than setting ``FLASK_APP`` each time you open a new terminal, you can288-use Flask's dotenv support to set environment variables automatically.170+The ``flask`` command supports setting any option for any command with171+environment variables. The variables are named like ``FLASK_OPTION`` or172+``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or173+``FLASK_RUN_PORT``.174 175+Rather than passing options every time you run a command, or environment176+variables every time you open a new terminal, you can use Flask's dotenv177+support to set environment variables automatically.178+179 If `python-dotenv`_ is installed, running the ``flask`` command will set291-environment variables defined in the files :file:`.env` and :file:`.flaskenv`.292-This can be used to avoid having to set ``FLASK_APP`` manually every time you293-open a new terminal, and to set configuration using environment variables294-similar to how some deployment services work.180+environment variables defined in the files ``.env`` and ``.flaskenv``.181+You can also specify an extra file to load with the ``--env-file``182+option. Dotenv files can be used to avoid having to set ``--app`` or183+``FLASK_APP`` manually, and to set configuration using environment184+variables similar to how some deployment services work.185 186 Variables set on the command line are used over those set in :file:`.env`,187 which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be188 used for public variables, such as ``FLASK_APP``, while :file:`.env` should not312 unmodified lines501 Custom Scripts502 --------------503 504 When you are using the app factory pattern, it may be more convenient to define615-your own Click script. Instead of using ``FLASK_APP`` and letting Flask load505+your own Click script. Instead of using ``--app`` and letting Flask load506 your application, you can create your own Click object and export it as a507 `console script`_ entry point.508 509 Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::25 unmodified lines535 },536 )537 538 Install the application in the virtualenv in editable mode and the custom649-script is available. Note that you don't need to set ``FLASK_APP``. ::539+script is available. Note that you don't need to set ``--app``. ::540 541 $ pip install -e .542 $ wiki run543 65 unmodified linesmodified:docs/config.rst+20 added-48 removed
45 unmodified lines46 ------------------------------47 48 The :data:`ENV` and :data:`DEBUG` config values are special because they49 may behave inconsistently if changed after the app has begun setting up.50-In order to set the environment and debug mode reliably, Flask uses51-environment variables.50+In order to set the environment and debug mode reliably, pass options to51+the ``flask`` command or use environment variables.52 53-The environment is used to indicate to Flask, extensions, and other54-programs, like Sentry, what context Flask is running in. It is55-controlled with the :envvar:`FLASK_ENV` environment variable and56-defaults to ``production``.53+The execution environment is used to indicate to Flask, extensions, and54+other programs, like Sentry, what context Flask is running in. It is55+controlled with the ``FLASK_ENV`` environment variable, or the56+``--env`` option when using the ``flask`` command, and defaults to57+``production``.58 58-Setting :envvar:`FLASK_ENV` to ``development`` will enable debug mode.59-``flask run`` will use the interactive debugger and reloader by default60-in debug mode. To control this separately from the environment, use the61-:envvar:`FLASK_DEBUG` flag.59+Setting ``--env development`` will enable debug mode. ``flask run`` will60+use the interactive debugger and reloader by default in debug mode. To61+control this separately from the environment, use the62+``--debug/--no-debug`` option or the ``FLASK_DEBUG`` environment63+variable.64 63-.. versionchanged:: 1.064- Added :envvar:`FLASK_ENV` to control the environment separately65- from debug mode. The development environment enables debug mode.66-65 To switch Flask to the development environment and enable debug mode,68-set :envvar:`FLASK_ENV`:66+set ``--env``:67 70-.. tabs::68+.. code-block:: text69 72- .. group-tab:: Bash70+ $ flask --app hello --env development run71 74- .. code-block:: text72+Using the options or environment variables as described above is73+recommended. While it is possible to set :data:`ENV` and :data:`DEBUG`74+in your config or code, this is strongly discouraged. They can't be read75+early by the ``flask`` command, and some systems or extensions may have76+already configured themselves based on a previous value.77 76- $ export FLASK_ENV=development77- $ flask run78 79- .. group-tab:: Fish80-81- .. code-block:: text82-83- $ set -x FLASK_ENV development84- $ flask run85-86- .. group-tab:: CMD87-88- .. code-block:: text89-90- > set FLASK_ENV=development91- > flask run92-93- .. group-tab:: Powershell94-95- .. code-block:: text96-97- > $env:FLASK_ENV = "development"98- > flask run99-100-Using the environment variables as described above is recommended. While101-it is possible to set :data:`ENV` and :data:`DEBUG` in your config or102-code, this is strongly discouraged. They can't be read early by the103-``flask`` command, and some systems or extensions may have already104-configured themselves based on a previous value.105-106-79 Builtin Configuration Values80 ----------------------------81 82 The following configuration values are used internally by Flask:704 unmodified linesmodified:docs/debugging.rst+11 added-65 removed
37 unmodified lines38 browser. It is protected by a pin, but still represents a major39 security risk. Do not run the development server or debugger in a40 production environment.41 42-To enable the debugger, run the development server with the43-``FLASK_ENV`` environment variable set to ``development``. This puts44-Flask in debug mode, which changes how it handles some errors, and45-enables the debugger and reloader.42+To enable the debugger, run the development server with the environment43+set to ``development``. This puts Flask in debug mode, which changes how44+it handles some errors, and enables the debugger and reloader.45 47-.. tabs::46+.. code-block:: text47 49- .. group-tab:: Bash48+ $ flask --app hello --env development run49 51- .. code-block:: text52-53- $ export FLASK_ENV=development54- $ flask run55-56- .. group-tab:: Fish57-58- .. code-block:: text59-60- $ set -x FLASK_ENV development61- $ flask run62-63- .. group-tab:: CMD64-65- .. code-block:: text66-67- > set FLASK_ENV=development68- > flask run69-70- .. group-tab:: Powershell71-72- .. code-block:: text73-74- > $env:FLASK_ENV = "development"75- > flask run76-77-``FLASK_ENV`` can only be set as an environment variable. When running50+``FLASK_ENV`` can also be set as an environment variable. When running51 from Python code, passing ``debug=True`` enables debug mode, which is79-mostly equivalent. Debug mode can be controlled separately from80-``FLASK_ENV`` with the ``FLASK_DEBUG`` environment variable as well.52+mostly equivalent. Debug mode can be controlled separately from the53+environment with the ``--debug/--no-debug`` option or the54+``FLASK_DEBUG`` environment variable.55 56 .. code-block:: python57 58 app.run(debug=True)16 unmodified lines75 When using an external debugger, the app should still be in debug mode,76 but it can be useful to disable the built-in debugger and reloader,77 which can interfere.78 105-When running from the command line:79+.. code-block:: text80 107-.. tabs::81+ $ flask --app hello --env development run --no-debugger --no-reload82 109- .. group-tab:: Bash110-111- .. code-block:: text112-113- $ export FLASK_ENV=development114- $ flask run --no-debugger --no-reload115-116- .. group-tab:: Fish117-118- .. code-block:: text119-120- $ set -x FLASK_ENV development121- $ flask run --no-debugger --no-reload122-123- .. group-tab:: CMD124-125- .. code-block:: text126-127- > set FLASK_ENV=development128- > flask run --no-debugger --no-reload129-130- .. group-tab:: Powershell131-132- .. code-block:: text133-134- > $env:FLASK_ENV = "development"135- > flask run --no-debugger --no-reload136-83 When running from Python:84 85 .. code-block:: python86 7 unmodified linesmodified:docs/quickstart.rst+19 added-96 removed
37 unmodified lines38 Save it as :file:`hello.py` or something similar. Make sure to not call39 your application :file:`flask.py` because this would conflict with Flask40 itself.41 42-To run the application, use the :command:`flask` command or43-:command:`python -m flask`. Before you can do that you need44-to tell your terminal the application to work with by exporting the45-``FLASK_APP`` environment variable:42+To run the application, use the ``flask`` command or43+``python -m flask``. You need to tell the Flask where your application44+is with the ``-app`` option.45 47-.. tabs::46+.. code-block:: text47 49- .. group-tab:: Bash48+ $ flask --app hello run49+ * Serving Flask app 'hello' (lazy loading)50+ * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)51 51- .. code-block:: text52-53- $ export FLASK_APP=hello54- $ flask run55- * Running on http://127.0.0.1:5000/56-57- .. group-tab:: Fish58-59- .. code-block:: text60-61- $ set -x FLASK_APP hello62- $ flask run63- * Running on http://127.0.0.1:5000/64-65- .. group-tab:: CMD66-67- .. code-block:: text68-69- > set FLASK_APP=hello70- > flask run71- * Running on http://127.0.0.1:5000/72-73- .. group-tab:: Powershell74-75- .. code-block:: text76-77- > $env:FLASK_APP = "hello"78- > flask run79- * Running on http://127.0.0.1:5000/80-52 .. admonition:: Application Discovery Behavior53 54 As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you84- don't have to set the ``FLASK_APP`` environment variable. See85- :doc:`/cli` for more details.55+ don't have to use ``--app``. See :doc:`/cli` for more details.56 57 This launches a very simple builtin server, which is good enough for58 testing but probably not what you want to use in production. For59 deployment options see :doc:`deploying/index`.23 unmodified lines83 84 This tells your operating system to listen on all public IPs.85 86 117-What to do if the Server does not Start118----------------------------------------119-120-In case the :command:`python -m flask` fails or :command:`flask`121-does not exist, there are multiple reasons this might be the case.122-First of all you need to look at the error message.123-124-Old Version of Flask125-````````````````````126-127-Versions of Flask older than 0.11 used to have different ways to start the128-application. In short, the :command:`flask` command did not exist, and129-neither did :command:`python -m flask`. In that case you have two options:130-either upgrade to newer Flask versions or have a look at :doc:`/server`131-to see the alternative method for running a server.132-133-Invalid Import Name134-```````````````````135-136-The ``FLASK_APP`` environment variable is the name of the module to import at137-:command:`flask run`. In case that module is incorrectly named you will get an138-import error upon start (or if debug is enabled when you navigate to the139-application). It will tell you what it tried to import and why it failed.140-141-The most common reason is a typo or because you did not actually create an142-``app`` object.143-144-87 Debug Mode88 ----------89 90 The ``flask run`` command can do more than just start the development12 unmodified lines103 browser. It is protected by a pin, but still represents a major104 security risk. Do not run the development server or debugger in a105 production environment.106 165-To enable all development features, set the ``FLASK_ENV`` environment166-variable to ``development`` before calling ``flask run``.107+To enable all development features, set the ``--env`` option to108+``development``.109 168-.. tabs::110+.. code-block:: text111 170- .. group-tab:: Bash112+ $ flask --app hello --env development run113+ * Serving Flask app 'hello' (lazy loading)114+ * Environment: development115+ * Debug mode: on116+ * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)117+ * Restarting with stat118+ * Debugger is active!119+ * Debugger PIN: nnn-nnn-nnn120 172- .. code-block:: text173-174- $ export FLASK_ENV=development175- $ flask run176-177- .. group-tab:: Fish178-179- .. code-block:: text180-181- $ set -x FLASK_ENV development182- $ flask run183-184- .. group-tab:: CMD185-186- .. code-block:: text187-188- > set FLASK_ENV=development189- > flask run190-191- .. group-tab:: Powershell192-193- .. code-block:: text194-195- > $env:FLASK_ENV = "development"196- > flask run197-121 See also:122 123 - :doc:`/server` and :doc:`/cli` for information about running in124 development mode.757 unmodified linesmodified:docs/reqcontext.rst+2 added-2 removed
225 unmodified lines226 associated with it is destroyed. If an error occurs during development,227 it is useful to delay destroying the data for debugging purposes.228 229 When the development server is running in development mode (the230-``FLASK_ENV`` environment variable is set to ``'development'``), the231-error and data will be preserved and shown in the interactive debugger.230+``--env`` option is set to ``'development'``), the error and data will231+be preserved and shown in the interactive debugger.232 233 This behavior can be controlled with the234 :data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it235 defaults to ``True`` in the development environment.30 unmodified linesmodified:docs/server.rst+15 added-8 removed
17 unmodified lines18 Command Line19 ------------20 21 The ``flask run`` command line script is the recommended way to run the22-development server. It requires setting the ``FLASK_APP`` environment23-variable to point to your application, and ``FLASK_ENV=development`` to24-fully enable development mode.22+development server. Use the ``--app`` option to point to your23+application, and the ``--env development`` option to fully enable24+development mode.25 26+.. code-block:: text27+28+ $ flask --app hello --env development run29+30+These options (and any others) can also be set using environment31+variables.32+33 .. tabs::34 35 .. group-tab:: Bash36 34 unmodified lines71 and using the CLI.72 73 .. note::74 68- Prior to Flask 1.0 the ``FLASK_ENV`` environment variable was not69- supported and you needed to enable debug mode by exporting70- ``FLASK_DEBUG=1``. This can still be used to control debug mode, but71- you should prefer setting the development environment as shown72- above.75+ Debug mode can be controlled separately from the development76+ environment with the ``--debug/--no-debug`` option or the77+ ``FLASK_DEBUG`` environment variable. This is how older versions of78+ Flask worked. You should prefer setting the development environment79+ as shown above.80 81 82 .. _address-already-in-use:83 89 unmodified linesmodified:examples/javascript/README.rst+1 added-2 removed
31 unmodified lines32 ---33 34 .. code-block:: text35 36- $ export FLASK_APP=js_example37- $ flask run36+ $ flask --app js_example run37 38 Open http://127.0.0.1:5000 in a browser.39 40 8 unmodified linesmodified:examples/tutorial/README.rst+3 added-12 removed
43 unmodified lines44 45 Run46 ---47 48-::48+.. code-block:: text49 50- $ export FLASK_APP=flaskr51- $ export FLASK_ENV=development52- $ flask init-db53- $ flask run50+ $ flask --app flaskr init-db51+ $ flask --app flaskr --env development run52 55-Or on Windows cmd::56-57- > set FLASK_APP=flaskr58- > set FLASK_ENV=development59- > flask init-db60- > flask run61-53 Open http://127.0.0.1:5000 in a browser.54 55 56 Test12 unmodified linesmodified:src/flask/cli.py+188 added-51 removed
1+from __future__ import annotations2+3 import ast4 import inspect5 import os6 import platform6 unmodified lines13 from threading import Lock14 from threading import Thread15 16 import click17+from click.core import ParameterSource18 from werkzeug.serving import is_running_from_reloader19 from werkzeug.utils import import_string20 21 from .globals import current_app22 from .helpers import get_debug_flag23 from .helpers import get_env24 from .helpers import get_load_dotenv25 26+if t.TYPE_CHECKING:27+ from .app import Flask28 29+30 class NoAppException(click.UsageError):31 """Raised if an application cannot be found or loaded."""32 33 17 unmodified lines51 return matches[0]52 elif len(matches) > 1:53 raise NoAppException(54 "Detected multiple Flask applications in module"49- f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"50- f" to specify the correct one."55+ f" '{module.__name__}'. Use '{module.__name__}:name'"56+ " to specify the correct one."57 )58 59 # Search for app factory functions.60 for attr_name in ("create_app", "make_app"):9 unmodified lines70 if not _called_with_wrong_args(app_factory):71 raise72 73 raise NoAppException(68- f"Detected factory {attr_name!r} in module {module.__name__!r},"74+ f"Detected factory '{attr_name}' in module '{module.__name__}',"75 " but could not call it without arguments. Use"70- f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""76+ f" '{module.__name__}:{attr_name}(args)'"77 " to specify arguments."78 ) from e79 80 raise NoAppException(81 "Failed to find Flask application or factory in module"76- f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"82+ f" '{module.__name__}'. Use '{module.__name__}:name'"83 " to specify one."84 )85 86 171 unmodified lines258 259 260 version_option = click.Option(261 ["--version"],256- help="Show the flask version",262+ help="Show the Flask version.",263 expose_value=False,264 callback=get_version,265 is_flag=True,266 is_eager=True,76 unmodified lines343 :class:`FlaskGroup` but you can also manually create it and pass it344 onwards as click object.345 """346 341- def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):347+ def __init__(348+ self,349+ app_import_path: str | None = None,350+ create_app: t.Callable[..., Flask] | None = None,351+ set_debug_flag: bool = True,352+ ) -> None:353 #: Optionally the import path for the Flask application.343- self.app_import_path = app_import_path or os.environ.get("FLASK_APP")354+ self.app_import_path = app_import_path355 #: Optionally a function that is passed the script info to create356 #: the instance of the application.357 self.create_app = create_app358 #: A dictionary with arbitrary data that can be associated with359 #: this script info.349- self.data = {}360+ self.data: t.Dict[t.Any, t.Any] = {}361 self.set_debug_flag = set_debug_flag351- self._loaded_app = None362+ self._loaded_app: Flask | None = None363 353- def load_app(self):364+ def load_app(self) -> Flask:365 """Loads the Flask app (if not yet loaded) and returns it. Calling366 this multiple times will just result in the already loaded app to367 be returned.368 """20 unmodified lines389 break390 391 if not app:392 raise NoAppException(382- "Could not locate a Flask application. You did not provide "383- 'the "FLASK_APP" environment variable, and a "wsgi.py" or '384- '"app.py" module was not found in the current directory.'393+ "Could not locate a Flask application. Use the"394+ " 'flask --app' option, 'FLASK_APP' environment"395+ " variable, or a 'wsgi.py' or 'app.py' file in the"396+ " current directory."397 )398 399 if self.set_debug_flag:400 # Update the app's debug flag through the descriptor so that52 unmodified lines453 kwargs.setdefault("cls", AppGroup)454 return click.Group.group(self, *args, **kwargs)455 456 457+def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:458+ if value is None:459+ return None460+461+ info = ctx.ensure_object(ScriptInfo)462+ info.app_import_path = value463+ return value464+465+466+# This option is eager so the app will be available if --help is given.467+# --help is also eager, so --app must be before it in the param list.468+# no_args_is_help bypasses eager processing, so this option must be469+# processed manually in that case to ensure FLASK_APP gets picked up.470+_app_option = click.Option(471+ ["-A", "--app"],472+ metavar="IMPORT",473+ help=(474+ "The Flask application or factory function to load, in the form 'module:name'."475+ " Module can be a dotted import or file path. Name is not required if it is"476+ " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to"477+ " pass arguments."478+ ),479+ is_eager=True,480+ expose_value=False,481+ callback=_set_app,482+)483+484+485+def _set_env(ctx: click.Context, param: click.Option, value: str | None) -> str | None:486+ if value is None:487+ return None488+489+ # Set with env var instead of ScriptInfo.load so that it can be490+ # accessed early during a factory function.491+ os.environ["FLASK_ENV"] = value492+ return value493+494+495+_env_option = click.Option(496+ ["-E", "--env"],497+ metavar="NAME",498+ help=(499+ "The execution environment name to set in 'app.env'. Defaults to"500+ " 'production'. 'development' will enable 'app.debug' and start the"501+ " debugger and reloader when running the server."502+ ),503+ expose_value=False,504+ callback=_set_env,505+)506+507+508+def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:509+ # If the flag isn't provided, it will default to False. Don't use510+ # that, let debug be set by env in that case.511+ source = ctx.get_parameter_source(param.name) # type: ignore[arg-type]512+513+ if source is not None and source in (514+ ParameterSource.DEFAULT,515+ ParameterSource.DEFAULT_MAP,516+ ):517+ return None518+519+ # Set with env var instead of ScriptInfo.load so that it can be520+ # accessed early during a factory function.521+ os.environ["FLASK_DEBUG"] = "1" if value else "0"522+ return value523+524+525+_debug_option = click.Option(526+ ["--debug/--no-debug"],527+ help="Set 'app.debug' separately from '--env'.",528+ expose_value=False,529+ callback=_set_debug,530+)531+532+533+def _env_file_callback(534+ ctx: click.Context, param: click.Option, value: str | None535+) -> str | None:536+ if value is None:537+ return None538+539+ import importlib540+541+ try:542+ importlib.import_module("dotenv")543+ except ImportError:544+ raise click.BadParameter(545+ "python-dotenv must be installed to load an env file.",546+ ctx=ctx,547+ param=param,548+ ) from None549+550+ # Don't check FLASK_SKIP_DOTENV, that only disables automatically551+ # loading .env and .flaskenv files.552+ load_dotenv(value)553+ return value554+555+556+# This option is eager so env vars are loaded as early as possible to be557+# used by other options.558+_env_file_option = click.Option(559+ ["-e", "--env-file"],560+ type=click.Path(exists=True, dir_okay=False),561+ help="Load environment variables from this file. python-dotenv must be installed.",562+ is_eager=True,563+ expose_value=False,564+ callback=_env_file_callback,565+)566+567+568 class FlaskGroup(AppGroup):569 """Special subclass of the :class:`AppGroup` group that supports570 loading more commands from the configured Flask app. Normally a571 developer does not have to interface with this class but there are10 unmodified lines582 directory to the directory containing the first file found.583 :param set_debug_flag: Set the app's debug flag based on the active584 environment585 586+ .. versionchanged:: 2.2587+ Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,588+ and ``-e/--env-file`` options.589+590 .. versionchanged:: 1.0591 If installed, python-dotenv will be used to load environment variables592 from :file:`.env` and :file:`.flaskenv` files.593 """594 595 def __init__(596 self,470- add_default_commands=True,471- create_app=None,472- add_version_option=True,473- load_dotenv=True,474- set_debug_flag=True,475- **extra,476- ):597+ add_default_commands: bool = True,598+ create_app: t.Callable[..., Flask] | None = None,599+ add_version_option: bool = True,600+ load_dotenv: bool = True,601+ set_debug_flag: bool = True,602+ **extra: t.Any,603+ ) -> None:604 params = list(extra.pop("params", None) or ())605+ # Processing is done with option callbacks instead of a group606+ # callback. This allows users to make a custom group callback607+ # without losing the behavior. --env-file must come first so608+ # that it is eagerly evaluated before --app.609+ params.extend((_env_file_option, _app_option, _env_option, _debug_option))610 611 if add_version_option:612 params.append(version_option)613 72 unmodified lines686 return sorted(rv)687 688 def make_context(689 self,558- info_name: t.Optional[str],559- args: t.List[str],560- parent: t.Optional[click.Context] = None,690+ info_name: str | None,691+ args: list[str],692+ parent: click.Context | None = None,693 **extra: t.Any,694 ) -> click.Context:695+ # Attempt to load .env and .flask env files. The --env-file696+ # option can cause another file to be loaded.697 if get_load_dotenv(self.load_dotenv):698 load_dotenv()699 700 if "obj" not in extra and "obj" not in self.context_settings:2 unmodified lines703 )704 705 return super().make_context(info_name, args, parent=parent, **extra)706 707+ def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:708+ if not args and self.no_args_is_help:709+ # Attempt to load --env-file and --app early in case they710+ # were given as env vars. Otherwise no_args_is_help will not711+ # see commands from app.cli.712+ _env_file_option.handle_parse_result(ctx, {}, [])713+ _app_option.handle_parse_result(ctx, {}, [])714 715+ return super().parse_args(ctx, args)716+717+718 def _path_is_ancestor(path, other):719 """Take ``other`` and remove the length of ``path`` from it. Then join it720 to ``path``. If it is the original value, ``path`` is an ancestor of721 ``other``."""722 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other723 724 581-def load_dotenv(path=None):725+def load_dotenv(path: str | os.PathLike | None = None) -> bool:726 """Load "dotenv" files in order of precedence to set environment variables.727 728 If an env var is already set it is not overwritten, so earlier files in the729 list are preferred over later files.4 unmodified lines734 735 :param path: Load the file at this location instead of searching.736 :return: ``True`` if a file was loaded.737 594- .. versionchanged:: 1.1.0595- Returns ``False`` when python-dotenv is not installed, or when596- the given path isn't a file.738+ .. versionchanged:: 2.0739+ The current directory is not changed to the location of the740+ loaded file.741 742 .. versionchanged:: 2.0743 When loading the env files, set the default encoding to UTF-8.744 745+ .. versionchanged:: 1.1.0746+ Returns ``False`` when python-dotenv is not installed, or when747+ the given path isn't a file.748+749 .. versionadded:: 1.0750 """751 try:752 import dotenv7 unmodified lines760 )761 762 return False763 616- # if the given path specifies the actual file then return True,617- # else False764+ # Always return after attempting to load a given path, don't load765+ # the default files.766 if path is not None:767 if os.path.isfile(path):768 return dotenv.load_dotenv(path, encoding="utf-8")769 770 return False771 624- new_dir = None772+ loaded = False773 774 for name in (".env", ".flaskenv"):775 path = dotenv.find_dotenv(name, usecwd=True)776 777 if not path:778 continue779 632- if new_dir is None:633- new_dir = os.path.dirname(path)634-780 dotenv.load_dotenv(path, encoding="utf-8")781+ loaded = True782 637- return new_dir is not None # at least one file was located and loaded783+ return loaded # True if at least one file was located and loaded.784 785 786 def show_server_banner(env, debug, app_import_path, eager_loading):787 """Show extra startup messages the first time the server is run,194 unmodified lines982 983 This server is for development purposes only. It does not provide984 the stability, security, or performance of production WSGI servers.985 840- The reloader and debugger are enabled by default if841- FLASK_ENV=development or FLASK_DEBUG=1.986+ The reloader and debugger are enabled by default with the987+ '--env development' or '--debug' options.988 """989+ app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)990 debug = get_debug_flag()991 992 if reload is None:993 reload = debug1 unmodified line995 if debugger is None:996 debugger = debug997 998 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)852- app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)999 1000 from werkzeug.serving import run_simple1001 1002 run_simple(113 unmodified lines1116 name="flask",1117 help="""\1118 A general utility script for Flask applications.1119 974-Provides commands from Flask, extensions, and the application. Loads the975-application defined in the FLASK_APP environment variable, or from a wsgi.py976-file. Setting the FLASK_ENV environment variable to 'development' will enable977-debug mode.978-979-\b980- {prefix}{cmd} FLASK_APP=hello.py981- {prefix}{cmd} FLASK_ENV=development982- {prefix}flask run983-""".format(984- cmd="export" if os.name == "posix" else "set",985- prefix="$ " if os.name == "posix" else "> ",986- ),1120+An application to load must be given with the '--app' option,1121+'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file1122+in the current directory.1123+""",1124 )1125 1126 1127 def main() -> None:5 unmodified linesmodified:src/flask/helpers.py+3 added-3 removed
46 unmodified lines47 return val.lower() not in ("0", "false", "no")48 49 50 def get_load_dotenv(default: bool = True) -> bool:51- """Get whether the user has disabled loading dotenv files by setting52- :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the53- files.51+ """Get whether the user has disabled loading default dotenv files by52+ setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load53+ the files.54 55 :param default: What to return if the env var isn't set.56 """57 val = os.environ.get("FLASK_SKIP_DOTENV")687 unmodified linesmodified:tests/conftest.py+1 added
16 unmodified lines17 :func:`._reset_os_environ` after each test.18 """19 mp = monkeypatch.MonkeyPatch()20 out = (21+ (os.environ, "FLASK_ENV_FILE", monkeypatch.notset),22 (os.environ, "FLASK_APP", monkeypatch.notset),23 (os.environ, "FLASK_ENV", monkeypatch.notset),24 (os.environ, "FLASK_DEBUG", monkeypatch.notset),25 (os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),173 unmodified linesmodified:CHANGES.rst+6 added
25 unmodified lines26 subclass sets this to ``False``, the view will not create a new27 instance on every request. :issue:`2520`.28 - A ``flask.cli.FlaskGroup`` Click group can be nested as a29 sub-command in a custom CLI. :issue:`3263`30+- Add ``--app``, ``--env``, and ``--debug`` options to the ``flask``31+ CLI, instead of requiring that they are set through environment32+ variables. :issue:`2836`33+- Add ``--env-file`` option to the ``flask`` CLI. This allows34+ specifying a dotenv file to load in addition to ``.env`` and35+ ``.flaskenv``. :issue:`3108`36 37 38 Version 2.1.339 -------------1291 unmodified lines