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 support for nested prefixes #8

Merged
merged 1 commit into from
Jan 2, 2018
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ Handling prefixes
host = env('HOST', 'localhost') # => 'lolcathost'
port = env.int('PORT', 5000) # => 3000

# nested prefixes are also supported:

# export MYAPP_DB_HOST=lolcathost
# export MYAPP_DB_PORT=10101

with env.prefixed('MYAPP_'):
with env.prefixed('DB_'):
db_host = env('HOST', 'lolcathost')
db_port = env.int('PORT', 10101)


Proxied variables
-----------------
Expand Down
8 changes: 6 additions & 2 deletions environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,13 @@ def read_env(path=None):
@contextlib.contextmanager
def prefixed(self, prefix):
"""Context manager for parsing envvars with a common prefix."""
self._prefix = prefix
old_prefix = self._prefix
if old_prefix is None:
self._prefix = prefix
else:
self._prefix = "{}{}".format(old_prefix, prefix)
yield self
self._prefix = None
self._prefix = old_prefix

def __getattr__(self, name, **kwargs):
try:
Expand Down
28 changes: 28 additions & 0 deletions tests/test_environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,3 +346,31 @@ def test_dump_with_prefixed(self, env):
env.int('INT') == 42
env('NOT_FOUND', 'mydefault') == 'mydefault'
assert env.dump() == {'APP_STR': 'foo', 'APP_INT': 42, 'APP_NOT_FOUND': 'mydefault'}

class TestNestedPrefix:

@pytest.fixture(autouse=True)
def default_environ(self, set_env):
set_env({'APP_STR': 'foo', 'APP_NESTED_INT': '42'})

def test_nested_prefixed(self, env):
with env.prefixed('APP_'):
with env.prefixed('NESTED_'):
assert env.int('INT') == 42
assert env('NOT_FOUND', 'mydefault') == 'mydefault'
assert env.str('STR') == 'foo'
assert env('NOT_FOUND', 'mydefault') == 'mydefault'

def test_dump_with_nested_prefixed(self, env):
with env.prefixed('APP_'):
with env.prefixed('NESTED_'):
env.int('INT') == 42
env('NOT_FOUND', 'mydefault') == 'mydefault'
env.str('STR') == 'foo'
env('NOT_FOUND', 'mydefault') == 'mydefault'
assert env.dump() == {
'APP_STR': 'foo',
'APP_NOT_FOUND': 'mydefault',
'APP_NESTED_INT': 42,
'APP_NESTED_NOT_FOUND': 'mydefault'
}