support Path in Config (#755)

* support Path in Config

* fix broken tests
This commit is contained in:
Trim21 2019-12-17 17:57:02 +08:00 committed by Tom Christie
parent 5c26cf6c40
commit d2b65c3c99
2 changed files with 11 additions and 3 deletions

View File

@ -1,6 +1,7 @@
import os import os
import typing import typing
from collections.abc import MutableMapping from collections.abc import MutableMapping
from pathlib import Path
class undefined: class undefined:
@ -46,7 +47,9 @@ environ = Environ()
class Config: class Config:
def __init__( 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: ) -> None:
self.environ = environ self.environ = environ
self.file_values = {} # type: typing.Dict[str, str] self.file_values = {} # type: typing.Dict[str, str]
@ -71,7 +74,7 @@ class Config:
return self._perform_cast(key, default, cast) return self._perform_cast(key, default, cast)
raise KeyError(f"Config '{key}' is missing, and has no default.") 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] file_values = {} # type: typing.Dict[str, str]
with open(file_name) as input_file: with open(file_name) as input_file:
for line in input_file.readlines(): for line in input_file.readlines():

View File

@ -5,6 +5,8 @@ import pytest
from starlette.config import Config, Environ, EnvironError from starlette.config import Config, Environ, EnvironError
from starlette.datastructures import URL, Secret from starlette.datastructures import URL, Secret
from pathlib import Path
def test_config(tmpdir, monkeypatch): def test_config(tmpdir, monkeypatch):
path = os.path.join(tmpdir, ".env") path = os.path.join(tmpdir, ".env")
@ -44,6 +46,10 @@ def test_config(tmpdir, monkeypatch):
with pytest.raises(ValueError): with pytest.raises(ValueError):
config.get("REQUEST_HOSTNAME", cast=bool) config.get("REQUEST_HOSTNAME", cast=bool)
config = Config(Path(path))
REQUEST_HOSTNAME= config("REQUEST_HOSTNAME")
assert REQUEST_HOSTNAME == "example.com"
config = Config() config = Config()
monkeypatch.setenv("STARLETTE_EXAMPLE_TEST", "123") monkeypatch.setenv("STARLETTE_EXAMPLE_TEST", "123")
monkeypatch.setenv("BOOL_AS_INT", "1") monkeypatch.setenv("BOOL_AS_INT", "1")
@ -54,7 +60,6 @@ def test_config(tmpdir, monkeypatch):
with pytest.raises(ValueError): with pytest.raises(ValueError):
config.get("BOOL_AS_INT", cast=bool) config.get("BOOL_AS_INT", cast=bool)
def test_environ(): def test_environ():
environ = Environ() environ = Environ()