Merge pull request #4720 from pallets/deprecate-env
Before adoption: this commit came in with the history the project adopted, so no landing records it.
deprecate `FLASK_ENV` and `app.env`
authored by David Lord · committed by GitHub · parents 3e5ca29, 30427a2 · Browse files · 14 files·+201 added−323 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+201 added−323 removed
- tests:+0 added−15 removed
- other:+201 added−308 removed
Provenance
- Commit
98ca00d- Tree
1671648- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
3e5ca29- Parent 2
30427a2
14 files changed+201 added−323 removed
added:docs/_static/pycharm-run-config.pngbinary
A binary file, added.
deleted:docs/_static/pycharm-runconfig.pngbinary
A binary file, deleted.
modified:docs/tutorial/factory.rst+3 added-4 removed
125 unmodified lines126 -------------------127 128 Now you can run your application using the ``flask`` command. From the129 terminal, tell Flask where to find your application, then run it in130-development mode. Remember, you should still be in the top-level130+debug mode. Remember, you should still be in the top-level131 ``flask-tutorial`` directory, not the ``flaskr`` package.132 133-Development mode shows an interactive debugger whenever a page raises an133+Debug mode shows an interactive debugger whenever a page raises an134 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 .. code-block:: text139 140- $ flask --app flaskr --env development run140+ $ flask --app flaskr --debug run141 142 You'll see output similar to this:143 144 .. code-block:: text145 146 * Serving Flask app "flaskr"147- * Environment: development147 * Debug mode: on148 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)149 * Restarting with stat150 * Debugger is active!12 unmodified linesmodified:docs/cli.rst+49 added-90 removed
69 unmodified lines70 71 The :func:`run <cli.run_command>` command will start the development server. It72 replaces the :meth:`Flask.run` method in most cases. ::73 74- $ flask run74+ $ flask --app hello run75 * Serving Flask app "hello"76 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)77 78 .. warning:: Do not use this command to run your application in production.6 unmodified lines85 server tries to start. See :ref:`address-already-in-use` for how to86 handle that.87 88 89-Open a Shell90-------------89+Debug Mode90+~~~~~~~~~~91 92-To explore the data in your application, you can start an interactive Python93-shell with the :func:`shell <cli.shell_command>` command. An application94-context will be active, and the app instance will be imported. ::92+In debug mode, the ``flask run`` command will enable the interactive debugger and the93+reloader by default, and make errors easier to see and debug. To enable debug mode, use94+the ``--debug`` option.95 96- $ flask shell97- Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux98- App: example [production]99- Instance: /home/david/Projects/pallets/flask/instance100- >>>96+.. code-block:: console97 102-Use :meth:`~Flask.shell_context_processor` to add other automatic imports.103-104-105-Environments106-------------107-108-.. versionadded:: 1.0109-110-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-121-.. code-block:: text122-123- $ flask --app hello --env development run98+ $ flask --app hello --debug run99 * Serving Flask app "hello"125- * Environment: development100 * Debug mode: on101 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)102 * Restarting with inotify reloader103 * Debugger is active!104 * Debugger PIN: 223-456-919105 106 133-Watch Extra Files with the Reloader134-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~107+Watch and Ignore Files with the Reloader108+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~109 136-When using development mode, the reloader will trigger whenever your137-Python code or imported modules change. The reloader can watch138-additional files with the ``--extra-files`` option. Multiple paths are139-separated with ``:``, or ``;`` on Windows.110+When using debug mode, the reloader will trigger whenever your Python code or imported111+modules change. The reloader can watch additional files with the ``--extra-files``112+option. Multiple paths are separated with ``:``, or ``;`` on Windows.113 114 .. code-block:: text115 116 $ flask run --extra-files file1:dirA/file2:dirB/117 * Running on http://127.0.0.1:8000/118 * Detected change in '/path/to/file1', reloading119 120+The reloader can also ignore files using :mod:`fnmatch` patterns with the121+``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on122+Windows.123 148-Ignore files with the Reloader149-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~124 151-The reloader can also ignore files using :mod:`fnmatch` patterns with152-the ``--exclude-patterns`` option. Multiple patterns are separated with153-``:``, or ``;`` on Windows.125+Open a Shell126+------------127 128+To explore the data in your application, you can start an interactive Python129+shell with the :func:`shell <cli.shell_command>` command. An application130+context will be active, and the app instance will be imported. ::131 156-Debug Mode157-----------132+ $ flask shell133+ Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux134+ App: example [production]135+ Instance: /home/david/Projects/pallets/flask/instance136+ >>>137 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.138+Use :meth:`~Flask.shell_context_processor` to add other automatic imports.139 140 141 .. _dotenv:142 384 unmodified lines527 528 PyCharm Integration529 -------------------530 555-PyCharm Professional provides a special Flask run configuration. For556-the Community Edition, we need to configure it to call the ``flask run``557-CLI command with the correct environment variables. These instructions558-should be similar for any other IDE you might want to use.531+PyCharm Professional provides a special Flask run configuration to run the development532+server. For the Community Edition, and for other commands besides ``run``, you need to533+create a custom run configuration. These instructions should be similar for any other534+IDE you use.535 560-In PyCharm, with your project open, click on *Run* from the menu bar and561-go to *Edit Configurations*. You'll be greeted by a screen similar to562-this:536+In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit537+Configurations*. You'll see a screen similar to this:538 564-.. image:: _static/pycharm-runconfig.png539+.. image:: _static/pycharm-run-config.png540 :align: center541 :class: screenshot567- :alt: Screenshot of PyCharms's run configuration settings.542+ :alt: Screenshot of PyCharm run configuration.543 569-There's quite a few options to change, but once we've done it for one570-command, we can easily copy the entire configuration and make a single571-tweak to give us access to other commands, including any custom ones you572-may implement yourself.544+Once you create a configuration for the ``flask run``, you can copy and change it to545+call any other command.546 574-Click the + (*Add New Configuration*) button and select *Python*. Give575-the configuration a name such as "flask run". For the ``flask run``576-command, check "Single instance only" since you can't run the server577-more than once at the same time.547+Click the *+ (Add New Configuration)* button and select *Python*. Give the configuration548+a name such as "flask run".549 579-Select *Module name* from the dropdown (**A**) then input ``flask``.550+Click the *Script path* dropdown and change it to *Module name*, then input ``flask``.551 581-The *Parameters* field (**B**) is set to the CLI command to execute582-(with any arguments). In this example we use ``run``, which will run583-the development server.552+The *Parameters* field is set to the CLI command to execute along with any arguments.553+This example uses ``--app hello --debug run``, which will run the development server in554+debug mode. ``--app hello`` should be the import or file with your Flask app.555 585-You can skip this next step if you're using :ref:`dotenv`. We need to586-add an environment variable (**C**) to identify our application. Click587-on the browse button and add an entry with ``FLASK_APP`` on the left and588-the Python import or file on the right (``hello`` for example). Add an589-entry with ``FLASK_ENV`` and set it to ``development``.556+If you installed your project as a package in your virtualenv, you may uncheck the557+*PYTHONPATH* options. This will more accurately match how you deploy later.558 591-Next we need to set the working directory (**D**) to be the folder where592-our application resides.559+Click *OK* to save and close the configuration. Select the configuration in the main560+PyCharm window and click the play button next to it to run the server.561 594-If you have installed your project as a package in your virtualenv, you595-may untick the *PYTHONPATH* options (**E**). This will more accurately596-match how you deploy the app later.597-598-Click *Apply* to save the configuration, or *OK* to save and close the599-window. Select the configuration in the main PyCharm window and click600-the play button next to it to run the server.601-602-Now that we have a configuration which runs ``flask run`` from within603-PyCharm, we can copy that configuration and alter the *Script* argument604-to run a different CLI command, e.g. ``flask shell``.562+Now that you have a configuration for ``flask run``, you can copy that configuration and563+change the *Parameters* argument to run a different CLI command.modified:docs/config.rst+25 added-43 removed
40 unmodified lines41 SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'42 )43 44 45-Environment and Debug Features46-------------------------------45+Debug Mode46+----------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, pass options to51-the ``flask`` command or use environment variables.48+The :data:`DEBUG` config value is special because it may behave inconsistently if49+changed after the app has begun setting up. In order to set debug mode reliably, use the50+``--debug`` option on the ``flask`` command.``flask run`` will use the interactive51+debugger and reloader by default in debug mode.52 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-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-65-To switch Flask to the development environment and enable debug mode,66-set ``--env``:67-53 .. code-block:: text54 70- $ flask --app hello --env development run55+ $ flask --app hello --debug run56 72-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.57+Using the option is recommended. While it is possible to set :data:`DEBUG` in your58+config or code, this is strongly discouraged. It can't be read early by the ``flask``59+command, and some systems or extensions may have already configured themselves based on60+a previous value.61 62 63 Builtin Configuration Values64 ----------------------------1 unmodified line66 The following configuration values are used internally by Flask:67 68 .. py:data:: ENV69 86- What environment the app is running in. Flask and extensions may87- enable behaviors based on the environment, such as enabling debug88- mode. The :attr:`~flask.Flask.env` attribute maps to this config89- key. This is set by the :envvar:`FLASK_ENV` environment variable and90- may not behave as expected if set in code.70+ What environment the app is running in. The :attr:`~flask.Flask.env` attribute maps71+ to this config key.72 92- **Do not enable development when deploying in production.**93-73 Default: ``'production'``74 75+ .. deprecated:: 2.276+ Will be removed in Flask 2.3. Use ``--debug`` instead.77+78 .. versionadded:: 1.079 80 .. py:data:: DEBUG81 100- Whether debug mode is enabled. When using ``flask run`` to start the101- development server, an interactive debugger will be shown for102- unhandled exceptions, and the server will be reloaded when code103- changes. The :attr:`~flask.Flask.debug` attribute maps to this104- config key. This is enabled when :data:`ENV` is ``'development'``105- and is overridden by the ``FLASK_DEBUG`` environment variable. It106- may not behave as expected if set in code.82+ Whether debug mode is enabled. When using ``flask run`` to start the development83+ server, an interactive debugger will be shown for unhandled exceptions, and the84+ server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute85+ maps to this config key. This is set with the ``FLASK_DEBUG`` environment variable.86+ It may not behave as expected if set in code.87 88 **Do not enable debug mode when deploying in production.**89 110- Default: ``True`` if :data:`ENV` is ``'development'``, or ``False``111- otherwise.90+ Default: ``False``91 92 .. py:data:: TESTING93 94 Enable testing mode. Exceptions are propagated rather than handled by the291 unmodified lines386 ``JSONIFY_MIMETYPE``, and ``JSONIFY_PRETTYPRINT_REGULAR`` will be387 removed in Flask 2.3. The default ``app.json`` provider has388 equivalent attributes instead.389 390+.. versionchanged:: 2.2391+ ``ENV`` will be removed in Flask 2.3. Use ``--debug`` instead.392 393+394 Configuring from Python Files395 -----------------------------396 397 Configuration becomes more useful if you can store it in a separate file,387 unmodified linesmodified:docs/debugging.rst+8 added-14 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 the environment43-set to ``development``. This puts Flask in debug mode, which changes how44-it handles some errors, and enables the debugger and reloader.42+The debugger is enabled by default when the development server is run in debug mode.43 44 .. code-block:: text45 48- $ flask --app hello --env development run46+ $ flask --app hello --debug run47 50-``FLASK_ENV`` can also be set as an environment variable. When running51-from Python code, passing ``debug=True`` enables debug mode, which is52-mostly equivalent. Debug mode can be controlled separately from the48+When running from Python code, passing ``debug=True`` enables debug mode, which is49+mostly equivalent.53-environment with the ``--debug/--no-debug`` option or the54-``FLASK_DEBUG`` environment variable.50 51 .. code-block:: python52 53 app.run(debug=True)54 60-:doc:`/server` and :doc:`/cli` have more information about running the61-debugger, debug mode, and development mode. More information about the62-debugger can be found in the `Werkzeug documentation63-<https://werkzeug.palletsprojects.com/debug/>`__.55+:doc:`/server` and :doc:`/cli` have more information about running the debugger and56+debug mode. More information about the debugger can be found in the `Werkzeug57+documentation <https://werkzeug.palletsprojects.com/debug/>`__.58 59 60 External Debuggers61 ------------------9 unmodified lines71 which can interfere.72 73 .. code-block:: text74 81- $ flask --app hello --env development run --no-debugger --no-reload75+ $ flask --app hello --debug run --no-debugger --no-reload76 77 When running from Python:78 79 .. code-block:: python8 unmodified linesmodified:docs/quickstart.rst+3 added-6 removed
102 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 107-To enable all development features, set the ``--env`` option to108-``development``.107+To enable debug mode, use the ``--debug`` option.108 109 .. code-block:: text110 112- $ flask --app hello --env development run111+ $ flask --app hello --debug run112 * Serving Flask app 'hello'114- * Environment: development113 * Debug mode: on114 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)115 * Restarting with stat116 * Debugger is active!117 * Debugger PIN: nnn-nnn-nnn118 119 See also:120 123-- :doc:`/server` and :doc:`/cli` for information about running in124- development mode.121+- :doc:`/server` and :doc:`/cli` for information about running in debug mode.122 - :doc:`/debugging` for information about using the built-in debugger123 and other debuggers.124 - :doc:`/logging` and :doc:`/errorhandling` to log errors and display125 nice error pages.774 unmodified linesmodified:docs/server.rst+17 added-69 removed
1 unmodified line2 3 Development Server4 ==================5 6-Flask provides a ``run`` command to run the application with a7-development server. In development mode, this server provides an8-interactive debugger and will reload when code is changed.6+Flask provides a ``run`` command to run the application with a development server. In7+debug mode, this server provides an interactive debugger and will reload when code is8+changed.9 10 .. warning::11 12 Do not use the development server when deploying to production. It4 unmodified lines17 18 Command Line19 ------------20 21-The ``flask run`` command line script is the recommended way to run the22-development server. Use the ``--app`` option to point to your23-application, and the ``--env development`` option to fully enable24-development mode.21+The ``flask run`` CLI command is the recommended way to run the development server. Use22+the ``--app`` option to point to your application, and the ``--debug`` option to enable23+debug mode.24 25 .. code-block:: text26 28- $ flask --app hello --env development run27+ $ flask --app hello --debug run28 30-These options (and any others) can also be set using environment31-variables.29+This enables debug mode, including the interactive debugger and reloader, and then30+starts the server on http://localhost:5000/. Use ``flask run --help`` to see the31+available options, and :doc:`/cli` for detailed instructions about configuring and using32+the CLI.33 33-.. tabs::34 35- .. group-tab:: Bash36-37- .. code-block:: text38-39- $ export FLASK_APP=hello40- $ export FLASK_ENV=development41- $ flask run42-43- .. group-tab:: Fish44-45- .. code-block:: text46-47- $ set -x FLASK_APP hello48- $ export FLASK_ENV=development49- $ flask run50-51- .. group-tab:: CMD52-53- .. code-block:: text54-55- > set FLASK_APP=hello56- > set FLASK_ENV=development57- > flask run58-59- .. group-tab:: Powershell60-61- .. code-block:: text62-63- > $env:FLASK_APP = "hello"64- > $env:FLASK_ENV = "development"65- > flask run66-67-This enables the development environment, including the interactive68-debugger and reloader, and then starts the server on69-http://localhost:5000/. Use ``flask run --help`` to see the available70-options, and :doc:`/cli` for detailed instructions about configuring71-and using the CLI.72-73-.. note::74-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-35 .. _address-already-in-use:36 37 Address already in use38 ~~~~~~~~~~~~~~~~~~~~~~57 unmodified lines96 97 In Code98 -------99 147-As an alternative to the ``flask run`` command, the development server148-can also be started from Python with the :meth:`Flask.run` method. This149-method takes arguments similar to the CLI options to control the server.150-The main difference from the CLI command is that the server will crash151-if there are errors when reloading.100+The development server can also be started from Python with the :meth:`Flask.run`101+method. This method takes arguments similar to the CLI options to control the server.102+The main difference from the CLI command is that the server will crash if there are103+errors when reloading. ``debug=True`` can be passed to enable debug mode.104 153-``debug=True`` can be passed to enable the debugger and reloader, but154-the ``FLASK_ENV=development`` environment variable is still required to155-fully enable development mode.105+Place the call in a main block, otherwise it will interfere when trying to import and106+run the application with a production server later.107 157-Place the call in a main block, otherwise it will interfere when trying158-to import and run the application with a production server later.159-108 .. code-block:: python109 110 if __name__ == "__main__":111 app.run(debug=True)4 unmodified linesmodified:examples/tutorial/README.rst+1 added-1 removed
46 unmodified lines47 48 .. code-block:: text49 50 $ flask --app flaskr init-db51- $ flask --app flaskr --env development run51+ $ flask --app flaskr --debug run52 53 Open http://127.0.0.1:5000 in a browser.54 55 13 unmodified linesmodified:src/flask/app.py+47 added-26 removed
43 unmodified lines44 from .globals import request_ctx45 from .globals import session46 from .helpers import _split_blueprint_path47 from .helpers import get_debug_flag48-from .helpers import get_env48 from .helpers import get_flashed_messages49 from .helpers import get_load_dotenv50 from .helpers import locked_cached_property51 from .json.provider import DefaultJSONProvider637 unmodified lines689 root_path = self.root_path690 if instance_relative:691 root_path = self.instance_path692 defaults = dict(self.default_config)694- defaults["ENV"] = get_env()693+ defaults["ENV"] = os.environ.get("FLASK_ENV") or "development"694 defaults["DEBUG"] = get_debug_flag()695 return self.config_class(root_path, defaults)696 697 def make_aborter(self) -> Aborter:149 unmodified lines847 for processor in self.shell_context_processors:848 rv.update(processor())849 return rv850 852- #: What environment the app is running in. Flask and extensions may853- #: enable behaviors based on the environment, such as enabling debug854- #: mode. This maps to the :data:`ENV` config key. This is set by the855- #: :envvar:`FLASK_ENV` environment variable and may not behave as856- #: expected if set in code.857- #:858- #: **Do not enable development when deploying in production.**859- #:860- #: Default: ``'production'``861- env = ConfigAttribute("ENV")851+ @property852+ def env(self) -> str:853+ """What environment the app is running in. This maps to the :data:`ENV` config854+ key.855 856+ **Do not enable development when deploying in production.**857+858+ Default: ``'production'``859+860+ .. deprecated:: 2.2861+ Will be removed in Flask 2.3.862+ """863+ import warnings864+865+ warnings.warn(866+ "'app.env' is deprecated and will be removed in Flask 2.3."867+ " Use 'app.debug' instead.",868+ DeprecationWarning,869+ stacklevel=2,870+ )871+ return self.config["ENV"]872+873+ @env.setter874+ def env(self, value: str) -> None:875+ import warnings876+877+ warnings.warn(878+ "'app.env' is deprecated and will be removed in Flask 2.3."879+ " Use 'app.debug' instead.",880+ DeprecationWarning,881+ stacklevel=2,882+ )883+ self.config["ENV"] = value884+885 @property886 def debug(self) -> bool:865- """Whether debug mode is enabled. When using ``flask run`` to start866- the development server, an interactive debugger will be shown for867- unhandled exceptions, and the server will be reloaded when code868- changes. This maps to the :data:`DEBUG` config key. This is869- enabled when :attr:`env` is ``'development'`` and is overridden870- by the ``FLASK_DEBUG`` environment variable. It may not behave as871- expected if set in code.887+ """Whether debug mode is enabled. When using ``flask run`` to start the888+ development server, an interactive debugger will be shown for unhandled889+ exceptions, and the server will be reloaded when code changes. This maps to the890+ :data:`DEBUG` config key. It may not behave as expected if set late.891 892 **Do not enable debug mode when deploying in production.**893 875- Default: ``True`` if :attr:`env` is ``'development'``, or876- ``False`` otherwise.894+ Default: ``False``895 """896 return self.config["DEBUG"]897 898 @debug.setter55 unmodified lines954 .. versionchanged:: 1.0955 If installed, python-dotenv will be used to load environment956 variables from :file:`.env` and :file:`.flaskenv` files.957 940- If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`941- environment variables will override :attr:`env` and942- :attr:`debug`.958+ The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.959 960 Threaded mode is enabled by default.961 962 .. versionchanged:: 0.1018 unmodified lines981 cli.load_dotenv()982 983 # if set, let env vars override previous values984 if "FLASK_ENV" in os.environ:969- self.env = get_env()985+ print(986+ "'FLASK_ENV' is deprecated and will not be used in"987+ " Flask 2.3. Use 'FLASK_DEBUG' instead.",988+ file=sys.stderr,989+ )990+ self.config["ENV"] = os.environ.get("FLASK_ENV") or "production"991 self.debug = get_debug_flag()992 elif "FLASK_DEBUG" in os.environ:993 self.debug = get_debug_flag()994 23 unmodified lines1018 options.setdefault("use_reloader", self.debug)1019 options.setdefault("use_debugger", self.debug)1020 options.setdefault("threaded", True)1021 1001- cli.show_server_banner(self.env, self.debug, self.name)1022+ cli.show_server_banner(self.debug, self.name)1023 1024 from werkzeug.serving import run_simple1025 1026 try:1357 unmodified linesmodified:src/flask/cli.py+16 added-46 removed
11 unmodified lines12 from operator import attrgetter13 14 import click15 from click.core import ParameterSource16+from werkzeug import run_simple17 from werkzeug.serving import is_running_from_reloader18 from werkzeug.utils import import_string19 20 from .globals import current_app21 from .helpers import get_debug_flag21-from .helpers import get_env22 from .helpers import get_load_dotenv23 24 if t.TYPE_CHECKING:25 from .app import Flask391 unmodified lines417 callback=_set_app,418 )419 420 421-def _set_env(ctx: click.Context, param: click.Option, value: str | None) -> str | None:422- if value is None:423- return None424-425- # Set with env var instead of ScriptInfo.load so that it can be426- # accessed early during a factory function.427- os.environ["FLASK_ENV"] = value428- return value429-430-431-_env_option = click.Option(432- ["-E", "--env"],433- metavar="NAME",434- help=(435- "The execution environment name to set in 'app.env'. Defaults to"436- " 'production'. 'development' will enable 'app.debug' and start the"437- " debugger and reloader when running the server."438- ),439- expose_value=False,440- callback=_set_env,441-)442-443-421 def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:422 # If the flag isn't provided, it will default to False. Don't use423 # that, let debug be set by env in that case.424 source = ctx.get_parameter_source(param.name) # type: ignore[arg-type]11 unmodified lines436 437 438 _debug_option = click.Option(439 ["--debug/--no-debug"],463- help="Set 'app.debug' separately from '--env'.",440+ help="Set debug mode.",441 expose_value=False,442 callback=_set_debug,443 )444 47 unmodified lines492 returns the loaded app.493 :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`494 files to set environment variables. Will also change the working495 directory to the directory containing the first file found.519- :param set_debug_flag: Set the app's debug flag based on the active520- environment496+ :param set_debug_flag: Set the app's debug flag.497 498 .. versionchanged:: 2.2523- Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,524- and ``-e/--env-file`` options.499+ Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.500 501 .. versionchanged:: 2.2502 An app context is pushed when running ``app.cli`` commands, so503 ``@with_appcontext`` is no longer required for those commands.16 unmodified lines520 # Processing is done with option callbacks instead of a group521 # callback. This allows users to make a custom group callback522 # without losing the behavior. --env-file must come first so523 # that it is eagerly evaluated before --app.549- params.extend((_env_file_option, _app_option, _env_option, _debug_option))524+ params.extend((_env_file_option, _app_option, _debug_option))525 526 if add_version_option:527 params.append(version_option)528 182 unmodified lines711 712 return loaded # True if at least one file was located and loaded.713 714 740-def show_server_banner(env, debug, app_import_path):715+def show_server_banner(debug, app_import_path):716 """Show extra startup messages the first time the server is run,717 ignoring the reloader.718 """719 if is_running_from_reloader():720 return721 722+ click.secho(723+ "WARNING: This is a development server. Do not use it in a production"724+ " deployment. Use a production WSGI server instead.",725+ fg="red",726+ bold=True,727+ )728+729 if app_import_path is not None:730 click.echo(f" * Serving Flask app '{app_import_path}'")731 750- click.echo(f" * Environment: {env}")751-752- if env == "production":753- click.secho(754- " WARNING: This is a development server. Do not use it in"755- " a production deployment.\n Use a production WSGI server"756- " instead.",757- fg="red",758- )759-732 if debug is not None:733 click.echo(f" * Debug mode: {'on' if debug else 'off'}")734 735 160 unmodified lines896 897 This server is for development purposes only. It does not provide898 the stability, security, or performance of production WSGI servers.899 928- The reloader and debugger are enabled by default with the929- '--env development' or '--debug' options.900+ The reloader and debugger are enabled by default with the '--debug'901+ option.902 """903 try:904 app = info.load_app()905 except Exception as e:18 unmodified lines924 925 if debugger is None:926 debugger = debug927 956- show_server_banner(get_env(), debug, info.app_import_path)928+ show_server_banner(debug, info.app_import_path)929 958- from werkzeug.serving import run_simple959-930 run_simple(931 host,932 port,933 app,125 unmodified linesmodified:src/flask/helpers.py+25 added-6 removed
27 unmodified lines28 def get_env() -> str:29 """Get the environment the app is running in, indicated by the30 :envvar:`FLASK_ENV` environment variable. The default is31 ``'production'``.32+33+ .. deprecated:: 2.234+ Will be removed in Flask 2.3.35 """36+ import warnings37+38+ warnings.warn(39+ "'FLASK_ENV' and 'get_env' are deprecated and will be removed"40+ " in Flask 2.3. Use 'FLASK_DEBUG' instead.",41+ DeprecationWarning,42+ stacklevel=2,43+ )44 return os.environ.get("FLASK_ENV") or "production"45 46 47 def get_debug_flag() -> bool:37- """Get whether debug mode should be enabled for the app, indicated38- by the :envvar:`FLASK_DEBUG` environment variable. The default is39- ``True`` if :func:`.get_env` returns ``'development'``, or ``False``40- otherwise.48+ """Get whether debug mode should be enabled for the app, indicated by the49+ :envvar:`FLASK_DEBUG` environment variable. The default is ``False``.50 """51 val = os.environ.get("FLASK_DEBUG")52 53 if not val:45- return get_env() == "development"54+ env = os.environ.get("FLASK_ENV")55 47- return val.lower() not in ("0", "false", "no")56+ if env is not None:57+ print(58+ "'FLASK_ENV' is deprecated and will not be used in"59+ " Flask 2.3. Use 'FLASK_DEBUG' instead.",60+ file=sys.stderr,61+ )62+ return env == "development"63 64+ return False65 66+ return val.lower() not in {"0", "false", "no"}67+68+69 def get_load_dotenv(default: bool = True) -> bool:70 """Get whether the user has disabled loading default dotenv files by71 setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load72 the files.633 unmodified linesmodified:tests/test_helpers.py-15 removed
4 unmodified lines5 import werkzeug.exceptions6 7 import flask8 from flask.helpers import get_debug_flag9-from flask.helpers import get_env9 10 11 class FakePath:12 """Fake object to represent a ``PathLike object``.307 unmodified lines320 else:321 assert get_debug_flag() == expected_flag322 assert get_debug_flag() == expected_default_flag323 325- @pytest.mark.parametrize(326- "env, ref_env, debug",327- [328- ("", "production", False),329- ("production", "production", False),330- ("development", "development", True),331- ("other", "other", False),332- ],333- )334- def test_get_env(self, monkeypatch, env, ref_env, debug):335- monkeypatch.setenv("FLASK_ENV", env)336- assert get_debug_flag() == debug337- assert get_env() == ref_env338-324 def test_make_response(self):325 app = flask.Flask(__name__)326 with app.test_request_context():327 rv = flask.helpers.make_response()21 unmodified linesmodified:CHANGES.rst+7 added-3 removed
21 unmodified lines22 and ``_request_ctx_stack.top`` are deprecated. Store data on23 ``g`` instead using a unique prefix, like24 ``g._extension_name_attr``.25 26+- The ``FLASK_ENV`` environment variable and ``app.env`` attribute are27+ deprecated, removing the distinction between development and debug28+ mode. Debug mode should be controlled directly using the ``--debug``29+ option or ``app.run(debug=True)``. :issue:`4714`30 - Add new customization points to the ``Flask`` app object for many31 previously global behaviors.32 33 - ``flask.url_for`` will call ``app.url_for``. :issue:`4568`29 unmodified lines63 subclass sets this to ``False``, the view will not create a new64 instance on every request. :issue:`2520`.65 - A ``flask.cli.FlaskGroup`` Click group can be nested as a66 sub-command in a custom CLI. :issue:`3263`63-- Add ``--app``, ``--env``, and ``--debug`` options to the ``flask``64- CLI, instead of requiring that they are set through environment65- variables. :issue:`2836`67+- Add ``--app`` and ``--debug`` options to the ``flask`` CLI, instead68+ of requiring that they are set through environment variables.69+ :issue:`2836`70 - Add ``--env-file`` option to the ``flask`` CLI. This allows71 specifying a dotenv file to load in addition to ``.env`` and72 ``.flaskenv``. :issue:`3108`73 - It is no longer required to decorate custom CLI commands on1308 unmodified lines