def get_conf(must_have_keys=DEAFULT_CONF_REQUIRED_KEYS,
config_file=DEFAULT_CONF_FILE,
env_config_file=DEFAULT_ENV_CONF_FILE,
with_pardir_fallback=True):
''' Read a configuration file, ensure all the `must_have_keys` are present
and return a config dict.
The file is read from `config_file` and if it's not there and it's a
default request, `conf/app_server.yaml` is used.
'''
if os.path.exists(config_file):
# this will load either the default conf file if it exists or the given config_file parameter
fh = open(config_file)
elif os.environ.get("BH_ENV") and os.path.exists(env_config_file.format(BH_ENV=os.environ["BH_ENV"])):
# environment is set in BH_ENV and corresponding conf file exists
fh = open(env_config_file.format(BH_ENV=os.environ["BH_ENV"]))
elif with_pardir_fallback and os.path.exists(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, 'conf', 'app_server.yaml')):
# fallback to local file for development
fh = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, 'conf', 'app_server.yaml'))
else:
raise Exception("Could not find a conf file")
conf = yaml.load(fh)
if not conf:
raise ValueError('Empty config file')
# Check that all the must_have_keys are present
config_keys = set(conf.keys())
missing_keys = list(must_have_keys.difference(config_keys))
if missing_keys != []:
keys_message = gen_missing_keys_error(missing_keys)
error_message = 'Invalid configuration file: ' + keys_message
raise ValueError(error_message)
return Struct(**conf) # Enables dot access
评论列表
文章目录