Skip to content

Commit

Permalink
Add Config.env_prefix option (#1990)
Browse files Browse the repository at this point in the history
* add Config.env_prefix option

* fix variable name in docs

* simplify test case

* rollback markdown formatting

* Update docs/config.md

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
  • Loading branch information
2 people authored and aminalaee committed Feb 13, 2023
1 parent bb188dc commit 7e83427
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
17 changes: 17 additions & 0 deletions docs/config.md
Expand Up @@ -113,6 +113,23 @@ from starlette.config import environ
environ['TESTING'] = 'TRUE'
```

## Reading prefixed environment variables

You can namespace the environment variables by setting `env_prefix` argument.

```python title="myproject/settings.py"
import os
from starlette.config import Config

os.environ['APP_DEBUG'] = 'yes'
os.environ['ENVIRONMENT'] = 'dev'

config = Config(env_prefix='APP_')

DEBUG = config('DEBUG') # lookups APP_DEBUG, returns "yes"
ENVIRONMENT = config('ENVIRONMENT') # lookups APP_ENVIRONMENT, raises KeyError as variable is not defined
```

## A full example

Structuring large applications can be complex. You need proper separation of
Expand Down
3 changes: 3 additions & 0 deletions starlette/config.py
Expand Up @@ -54,8 +54,10 @@ def __init__(
self,
env_file: typing.Optional[typing.Union[str, Path]] = None,
environ: typing.Mapping[str, str] = environ,
env_prefix: str = "",
) -> None:
self.environ = environ
self.env_prefix = env_prefix
self.file_values: typing.Dict[str, str] = {}
if env_file is not None and os.path.isfile(env_file):
self.file_values = self._read_file(env_file)
Expand Down Expand Up @@ -103,6 +105,7 @@ def get(
cast: typing.Optional[typing.Callable] = None,
default: typing.Any = undefined,
) -> typing.Any:
key = self.env_prefix + key
if key in self.environ:
value = self.environ[key]
return self._perform_cast(key, value, cast)
Expand Down
10 changes: 10 additions & 0 deletions tests/test_config.py
Expand Up @@ -127,3 +127,13 @@ def test_environ():
environ = Environ()
assert list(iter(environ)) == list(iter(os.environ))
assert len(environ) == len(os.environ)


def test_config_with_env_prefix(tmpdir, monkeypatch):
config = Config(
environ={"APP_DEBUG": "value", "ENVIRONMENT": "dev"}, env_prefix="APP_"
)
assert config.get("DEBUG") == "value"

with pytest.raises(KeyError):
config.get("ENVIRONMENT")

0 comments on commit 7e83427

Please sign in to comment.