在日常开发小脚本时,经常要使用配置文件,以下是我在日常开发中总结的自己的常用的使用配置文件的方法:
config.conf
1. 核心用法
def get_config(self, section, key):
config = ConfigParser.ConfigParser()
path = os.path.split(os.path.realpath(__file__))[0] + '/config.conf'
config.read(path)
return config.get(section, key)
2. 使用示例
这个应该是我最常用的方案,python自带了ConfigParser,能够解析以下格式文件:
# ./config.conf
[api_filter_db]
dbhost = xxx.xxx.xxx.xxx
dbport = 3306
dbname = yyy
dbuser = root
dbpassword = zzz
dbcharset = utf8
[mshow_db]
dbhost = xxx.xxx.xxx.xxx
dbport = 3306
dbname = yyy
dbuser = root
dbpassword = zzz
dbcharset = utf8
# ./get_config.py
class Utils(object):
def get_config(self, section, key):
config = ConfigParser.ConfigParser()
path = os.path.split(os.path.realpath(__file__))[0] + '/config.conf'
config.read(path)
return config.get(section, key)
#可以引用get_config函数
class DoSomething(Utils):
conn = MySQLdb.connect(
host=self.get_config('api_filter_db', 'dbhost'),
port=int(self.get_config('api_filter_db', 'dbport')),
user=self.get_config('api_filter_db', 'dbuser'),
passwd=self.get_config('api_filter_db', 'dbpassword'),
db=self.get_config('api_filter_db', 'dbname'),
charset=self.get_config('api_filter_db', 'dbcharset')
)
cursor = conn.cursor()
YAML
YAML也是一种比较常用的配置文件方案,平时用ansible会用的比较多,要解析yaml文件,需要安装一个第三方的包:yaml
# pip install yaml
1. 核心用法
# ./get_config.py
class Utils(object):
def get_config_yaml(self, section):
path = os.path.split(os.path.realpath(__file__))[0] + '/config.yaml'
config = yaml.load(file(config)) # {'mail': ['xx@zz.cn', 'yy@zz.cn'], 'phone': [1111111, 2222222, 3333333]}
return config.get(section)
2. 使用示例
YAML能够解析以下格式文件:
mail:
- xx@zz.cn
- yy@zz.cn
phone:
- 1111111
- 2222222
- 3333333
yaml解析后生成字典,内部数据组成一个数组:
{'mail': ['xx@zz.cn', 'yy@zz.cn'], 'phone': [1111111, 2222222, 3333333]}
函数根据提供的参数返回其中的数据组值。