From d787f607c2e21d9598336e10074414241964a9db Mon Sep 17 00:00:00 2001 From: Eero af Heurlin Date: Tue, 6 Feb 2024 23:28:47 +0200 Subject: [PATCH 1/2] Do not break old documented functionality, add flag to raise warning on missing .env file, document the flag --- docs/config.md | 3 ++- starlette/config.py | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/config.md b/docs/config.md index d7faa281a..45b9d2a3a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -11,7 +11,8 @@ from starlette.config import Config from starlette.datastructures import CommaSeparatedStrings, Secret # Config will be read from environment variables and/or ".env" files. -config = Config(".env") +# If warn_missing is set then warning is given if .env -file is not found. +config = Config(".env", warn_missing=True) DEBUG = config('DEBUG', cast=bool, default=False) DATABASE_URL = config('DATABASE_URL') diff --git a/starlette/config.py b/starlette/config.py index 75a097724..2479931ba 100644 --- a/starlette/config.py +++ b/starlette/config.py @@ -2,6 +2,7 @@ import os import typing +import warnings from pathlib import Path @@ -56,13 +57,17 @@ def __init__( env_file: str | Path | None = None, environ: typing.Mapping[str, str] = environ, env_prefix: str = "", + *, + warn_missing: bool = False, ) -> None: self.environ = environ self.env_prefix = env_prefix self.file_values: typing.Dict[str, str] = {} if env_file is not None: if not os.path.isfile(env_file): - raise FileNotFoundError(f"Config file '{env_file}' not found.") + if warn_missing: + warnings.warn(f"{env_file} not found") + return self.file_values = self._read_file(env_file) @typing.overload From ea27aca00878971bbe96c1246b7dd3311a5fcbda Mon Sep 17 00:00:00 2001 From: Eero af Heurlin Date: Tue, 6 Feb 2024 23:43:08 +0200 Subject: [PATCH 2/2] update test for missing .env file behaviour --- tests/test_config.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/test_config.py b/tests/test_config.py index 4974ffdb0..eb19a8c04 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,5 +1,6 @@ import os import typing +import warnings from pathlib import Path from typing import Any, Optional @@ -105,11 +106,15 @@ def cast_to_int(v: typing.Any) -> int: config.get("BOOL_AS_INT", cast=bool) -def test_missing_env_file_raises(tmpdir: Path) -> None: +def test_missing_env_file_warns_only_if_requested(tmpdir: Path) -> None: path = os.path.join(tmpdir, ".env") - with pytest.raises(FileNotFoundError, match=f"Config file '{path}' not found."): + with warnings.catch_warnings(record=True) as caught: Config(path) + assert not caught + with pytest.raises(UserWarning): + Config(path, warn_missing=True) + assert caught def test_environ() -> None: