Skip to content

Commit

Permalink
Merge pull request #8 from gvialetto/nested-prefixes
Browse files Browse the repository at this point in the history
Add support for nested prefixes
  • Loading branch information
sloria authored Jan 2, 2018
2 parents 2a2a89c + 0fa135b commit ba46c60
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
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'
}

0 comments on commit ba46c60

Please sign in to comment.