deprecate FLASK_ENV
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 4c08e3a · Browse files · 5 files·+95 added−96 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+95 added−96 removed
- tests:+0 added−15 removed
- other:+95 added−81 removed
Provenance
- Commit
ef95998- Tree
1839253- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
4c08e3a
5 files changed+95 added−96 removed
modified: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