diff --git a/starlette/config.py b/starlette/config.py index 68ae7b45..4839fca0 100644 --- a/starlette/config.py +++ b/starlette/config.py @@ -1,6 +1,7 @@ import os import typing from collections.abc import MutableMapping +from pathlib import Path class undefined: @@ -46,7 +47,9 @@ environ = Environ() class Config: def __init__( - self, env_file: str = None, environ: typing.Mapping[str, str] = environ + self, + env_file: typing.Union[str, Path] = None, + environ: typing.Mapping[str, str] = environ, ) -> None: self.environ = environ self.file_values = {} # type: typing.Dict[str, str] @@ -71,7 +74,7 @@ class Config: return self._perform_cast(key, default, cast) raise KeyError(f"Config '{key}' is missing, and has no default.") - def _read_file(self, file_name: str) -> typing.Dict[str, str]: + def _read_file(self, file_name: typing.Union[str, Path]) -> typing.Dict[str, str]: file_values = {} # type: typing.Dict[str, str] with open(file_name) as input_file: for line in input_file.readlines(): diff --git a/tests/test_config.py b/tests/test_config.py index f0ea1d45..6002bc1e 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -5,6 +5,8 @@ import pytest from starlette.config import Config, Environ, EnvironError from starlette.datastructures import URL, Secret +from pathlib import Path + def test_config(tmpdir, monkeypatch): path = os.path.join(tmpdir, ".env") @@ -44,6 +46,10 @@ def test_config(tmpdir, monkeypatch): with pytest.raises(ValueError): config.get("REQUEST_HOSTNAME", cast=bool) + config = Config(Path(path)) + REQUEST_HOSTNAME= config("REQUEST_HOSTNAME") + assert REQUEST_HOSTNAME == "example.com" + config = Config() monkeypatch.setenv("STARLETTE_EXAMPLE_TEST", "123") monkeypatch.setenv("BOOL_AS_INT", "1") @@ -54,7 +60,6 @@ def test_config(tmpdir, monkeypatch): with pytest.raises(ValueError): config.get("BOOL_AS_INT", cast=bool) - def test_environ(): environ = Environ()