方案二pyhocon
pyhocon是一个python的配置管理库
pyhocon的一个作用是可以直接在配置文件中使用${}的方式引用,pyhocon解析时会自动实现如上resolveEnv的逻辑,对应环境变量。
官网如下:
https://github.com/chimpler/pyhocon
配置文件如下:
default.conf
databases {
# MySQL
active = true
enable_logging = false
resolver = null
# you can use substitution with unquoted strings. If it it not found in the document, it defaults to environment variables
home_dir = ${HOME} # you can substitute with environment variables
"mysql" = {
host = "abc.com" # change it
port = 3306 # default
username: scott // can use : or =
password = tiger, // can optionally use a comma
// number of retries
retries = 3
}
}
${HOME}在解析使用解析时会自动获取到环境变量中的HOME
使用方式
from pyhocon import ConfigFactory
conf = ConfigFactory.parse_file('samples/database.conf')
host = conf.get_string('databases.mysql.host')
same_host = conf.get('databases.mysql.host')
same_host = conf['databases.mysql.host']
same_host = conf['databases']['mysql.host']
port = conf['databases.mysql.port']
username = conf['databases']['mysql']['username']
password = conf.get_config('databases')['mysql.password']
password = conf.get('databases.mysql.password', 'default_password') # use default value if key not found |