Last active
June 10, 2019 16:13
-
-
Save daniil-konovalenko/71d0fbf77f56c3d1eccc546537d18944 to your computer and use it in GitHub Desktop.
Convert dict-like config to a list of environment variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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