Skip to content
Myr

update env file precedence (#5630)

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 ce08bc7, 2c31603 · Browse files · 3 files+90 added−47 removed
This commit

State

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

Diff stats

3 files+90 added−47 removed

  • tests:+20 added−4 removed
  • other:+70 added−43 removed

3 files+90 added−47 removed

modified:src/flask/cli.py+67 added-43 removed
295 unmodified lines
296 to click. In future versions of Flask this object will most likely play297 a bigger role. Typically it's created automatically by the298 :class:`FlaskGroup` but you can also manually create it and pass it299 onwards as click object.300301 .. versionchanged:: 3.1302 Added the ``load_dotenv_defaults`` parameter and attribute.303 """304305 def __init__(306 self,307 app_import_path: str | None = None,308 create_app: t.Callable[..., Flask] | None = None,309 set_debug_flag: bool = True,310 load_dotenv_defaults: bool = True,311 ) -> None:312 #: Optionally the import path for the Flask application.313 self.app_import_path = app_import_path314 #: Optionally a function that is passed the script info to create
2 unmodified lines
317 #: A dictionary with arbitrary data that can be associated with318 #: this script info.319 self.data: dict[t.Any, t.Any] = {}320 self.set_debug_flag = set_debug_flag321322 self.load_dotenv_defaults = get_load_dotenv(load_dotenv_defaults)323 """Whether default ``.flaskenv`` and ``.env`` files should be loaded.324325 ``ScriptInfo`` doesn't load anything, this is for reference when doing326 the load elsewhere during processing.327328 .. versionadded:: 3.1329 """330331 self._loaded_app: Flask | None = None332333 def load_app(self) -> Flask:334 """Loads the Flask app (if not yet loaded) and returns it. Calling
157 unmodified lines
492493def _env_file_callback(494 ctx: click.Context, param: click.Option, value: str | None495) -> str | None:482 if value is None:483 return None484485 import importlib486496 try:488 importlib.import_module("dotenv")497 import dotenv # noqa: F401498 except ImportError:499 # Only show an error if a value was passed, otherwise we still want to500 # call load_dotenv and show a message without exiting.501 if value is not None:490 raise click.BadParameter(491 "python-dotenv must be installed to load an env file.",492 ctx=ctx,493 param=param,494 ) from None502 raise click.BadParameter(503 "python-dotenv must be installed to load an env file.",504 ctx=ctx,505 param=param,506 ) from None507496 # Don't check FLASK_SKIP_DOTENV, that only disables automatically497 # loading .env and .flaskenv files.498 load_dotenv(value)508 # Load if a value was passed, or we want to load default files, or both.509 if value is not None or ctx.obj.load_dotenv_defaults:510 load_dotenv(value, load_defaults=ctx.obj.load_dotenv_defaults)511512 return value513514515# This option is eager so env vars are loaded as early as possible to be516# used by other options.517_env_file_option = click.Option(518 ["-e", "--env-file"],519 type=click.Path(exists=True, dir_okay=False),507 help="Load environment variables from this file. python-dotenv must be installed.",520 help=(521 "Load environment variables from this file, taking precedence over"522 " those set by '.env' and '.flaskenv'. Variables set directly in the"523 " environment take highest precedence. python-dotenv must be installed."524 ),525 is_eager=True,526 expose_value=False,527 callback=_env_file_callback,528)
15 unmodified lines
544 files to set environment variables. Will also change the working545 directory to the directory containing the first file found.546 :param set_debug_flag: Set the app's debug flag.547548 .. versionchanged:: 3.1549 ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files.550551 .. versionchanged:: 2.2552 Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.553554 .. versionchanged:: 2.2
118 unmodified lines
673 # not in a __name__ == __main__ guard, it would start the server674 # when importing, blocking whatever command is being called.675 os.environ["FLASK_RUN_FROM_CLI"] = "true"676657 # Attempt to load .env and .flask env files. The --env-file658 # option can cause another file to be loaded.659 if get_load_dotenv(self.load_dotenv):660 load_dotenv()661677 if "obj" not in extra and "obj" not in self.context_settings:678 extra["obj"] = ScriptInfo(664 create_app=self.create_app, set_debug_flag=self.set_debug_flag679 create_app=self.create_app,680 set_debug_flag=self.set_debug_flag,681 load_dotenv_defaults=self.load_dotenv,682 )683684 return super().make_context(info_name, args, parent=parent, **extra)685
14 unmodified lines
700 ``other``."""701 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other702703687def load_dotenv(path: str | os.PathLike[str] | None = None) -> bool:688 """Load "dotenv" files in order of precedence to set environment variables.704def load_dotenv(705 path: str | os.PathLike[str] | None = None, load_defaults: bool = True706) -> bool:707 """Load "dotenv" files to set environment variables. A given path takes708 precedence over ``.env``, which takes precedence over ``.flaskenv``. After709 loading and combining these files, values are only set if the key is not710 already set in ``os.environ``.711690 If an env var is already set it is not overwritten, so earlier files in the691 list are preferred over later files.692712 This is a no-op if `python-dotenv`_ is not installed.713714 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme715697 :param path: Load the file at this location instead of searching.698 :return: ``True`` if a file was loaded.716 :param path: Load the file at this location.717 :param load_defaults: Search for and load the default ``.flaskenv`` and718 ``.env`` files.719 :return: ``True`` if at least one env var was loaded.720721 .. versionchanged:: 3.1722 Added the ``load_defaults`` parameter. A given path takes precedence723 over default files.724725 .. versionchanged:: 2.0726 The current directory is not changed to the location of the727 loaded file.728
10 unmodified lines
739 import dotenv740 except ImportError:741 if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):742 click.secho(718 " * Tip: There are .env or .flaskenv files present."719 ' Do "pip install python-dotenv" to use them.',743 " * Tip: There are .env files present. Install python-dotenv"744 " to use them.",745 fg="yellow",746 err=True,747 )748749 return False750726 # Always return after attempting to load a given path, don't load727 # the default files.728 if path is not None:729 if os.path.isfile(path):730 return dotenv.load_dotenv(path, encoding="utf-8")751 data: dict[str, str | None] = {}752732 return False753 if load_defaults:754 for default_name in (".flaskenv", ".env"):755 if not (default_path := dotenv.find_dotenv(default_name, usecwd=True)):756 continue757734 loaded = False758 data |= dotenv.dotenv_values(default_path, encoding="utf-8")759736 for name in (".env", ".flaskenv"):737 path = dotenv.find_dotenv(name, usecwd=True)760 if path is not None and os.path.isfile(path):761 data |= dotenv.dotenv_values(path, encoding="utf-8")762739 if not path:763 for key, value in data.items():764 if key in os.environ or value is None:765 continue766742 dotenv.load_dotenv(path, encoding="utf-8")743 loaded = True767 os.environ[key] = value768745 return loaded # True if at least one file was located and loaded.769 return bool(data) # True if at least one env var was loaded.770771772def show_server_banner(debug: bool, app_import_path: str | None) -> None:773 """Show extra startup messages the first time the server is run,
360 unmodified lines
modified:tests/test_cli.py+20 added-4 removed
396 unmodified lines
397398def test_no_command_echo_loading_error():399 from flask.cli import cli400401 try:401 runner = CliRunner(mix_stderr=False)402 runner = CliRunner(mix_stderr=False)403 except (DeprecationWarning, TypeError):404 # Click >= 8.2405 runner = CliRunner()406407 result = runner.invoke(cli, ["missing"])408 assert result.exit_code == 2409 assert "FLASK_APP" in result.stderr410 assert "Usage:" in result.stderr
1 unmodified line
412413def test_help_echo_loading_error():414 from flask.cli import cli415416 try:411 runner = CliRunner(mix_stderr=False)417 runner = CliRunner(mix_stderr=False)418 except (DeprecationWarning, TypeError):419 # Click >= 8.2420 runner = CliRunner()421422 result = runner.invoke(cli, ["--help"])423 assert result.exit_code == 0424 assert "FLASK_APP" in result.stderr425 assert "Usage:" in result.stdout
3 unmodified lines
429 def create_app():430 raise Exception("oh no")431432 cli = FlaskGroup(create_app=create_app)433434 try:423 runner = CliRunner(mix_stderr=False)435 runner = CliRunner(mix_stderr=False)436 except (DeprecationWarning, TypeError):437 # Click >= 8.2438 runner = CliRunner()439440 result = runner.invoke(cli, ["--help"])441 assert result.exit_code == 0442 assert "Exception: oh no" in result.stderr443 assert "Usage:" in result.stdout
108 unmodified lines
552 assert os.environ["EGGS"] == "3"553 # test env file encoding554 assert os.environ["HAM"] == "火腿"555 # Non existent file should not load540 assert not load_dotenv("non-existent-file")556 assert not load_dotenv("non-existent-file", load_defaults=False)557558559@need_dotenv560def test_dotenv_path(monkeypatch):
142 unmodified lines
modified:CHANGES.rst+3 added
15 unmodified lines
16 ``MAX_FORM_MEMORY_SIZE`` and ``MAX_FORM_PARTS`` config. Added documentation17 about resource limits to the security page. :issue:`5625`18- Add support for the ``Partitioned`` cookie attribute (CHIPS), with the19 ``SESSION_COOKIE_PARTITIONED`` config. :issue`5472`20- ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files.21 ``load_dotenv`` loads default files in addition to a path unless22 ``load_defaults=False`` is passed. :issue:`5628`232425Version 3.0.326-------------
1563 unmodified lines