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

Work in progress: Replicate Django-environ FileAwareEnv #295

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
19 changes: 18 additions & 1 deletion environs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ def _get_from_environ(
proxy env key.
"""
env_key = self._get_key(key, omit_prefix=proxied)
value = os.environ.get(env_key, default)
value = self._get_value(env_key, default)
if hasattr(value, "strip"):
expand_match = self.expand_vars and _EXPANDED_VAR_PATTERN.match(value)
if expand_match: # Full match expand_vars - special case keep default
Expand Down Expand Up @@ -535,3 +535,20 @@ def _expand_vars(self, parsed_key, value):

def _get_key(self, key: _StrType, *, omit_prefix: _BoolType = False) -> _StrType:
return self._prefix + key if self._prefix and not omit_prefix else key

@staticmethod
def _get_value(env_key, default):
return os.environ.get(env_key, default)


class FileAwareEnv(Env):
"""An environment variable reader that supports reading values from files."""

@staticmethod
def _get_value(env_key, default):
file_key = env_key + "_FILE"
if file_location := os.environ.get(file_key, None):
return Path(file_location).read_text()
else:
return os.environ.get(env_key, default)

15 changes: 15 additions & 0 deletions tests/test_environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,3 +837,18 @@ def test_composite_types(self, env, set_env):
"foo": "bar",
"wget_params": '--header="Referer: https://radiocut.fm/"',
}


class TestFileAwareEnv:
@pytest.fixture
def env(self):
return environs.FileAwareEnv(expand_vars=True)

def test_full_expand_vars(self, env, set_env):
set_env(
{
"MAIN": "legacy_value",
"MAIN_FILE": HERE / "subfolder/.another.env",
}
)
assert env.str("MAIN") == "CUSTOM_STRING=bar\n"