Skip to content

Instantly share code, notes, and snippets.

@daniil-konovalenko
Last active June 10, 2019 16:13
Show Gist options
  • Save daniil-konovalenko/71d0fbf77f56c3d1eccc546537d18944 to your computer and use it in GitHub Desktop.
Save daniil-konovalenko/71d0fbf77f56c3d1eccc546537d18944 to your computer and use it in GitHub Desktop.
Convert dict-like config to a list of environment variables
"""
Convert a dict-like config to a list of environment variables, discarding values
>>> config_to_envs(dict(
... server=dict(port=8000),
... database=dict(dsn='postgres://postgres:password@host:5432/postgres'),
... debug=True))
['SERVER_PORT', 'DATABASE_DSN', 'DEBUG']
>>> config_to_envs(dict(
... server=dict(port=8000),
... database=dict(dsn='postgres://postgres:password@host:5432/postgres'),
... debug=True), keep_values=True)
['SERVER_PORT=8000', 'DATABASE_DSN=postgres://postgres:password@host:5432/postgres', 'DEBUG=True']
"""
from typing import Dict, List, Union
def config_to_envs(config: Dict, keep_values=False) -> List[str]:
result = []
def _flatten(cfg: Union[dict, str], name=''):
if type(cfg) == dict:
for key, value in cfg.items():
if name:
_flatten(value, name=f'{name.upper()}_{key.upper()}')
else:
_flatten(value, name=key.upper())
else:
if keep_values:
value = cfg
result.append(f'{name}={value}')
else:
result.append(name)
_flatten(config)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment