Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore old documented functionality, add optional warning, document the warning #2486

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
7 changes: 6 additions & 1 deletion starlette/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os
import typing
import warnings
from pathlib import Path


Expand Down Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import typing
import warnings
from pathlib import Path
from typing import Any, Optional

Expand Down Expand Up @@ -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:
Expand Down
Loading