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

Add Config.env_prefix option #1990

Merged
merged 6 commits into from Jan 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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")