背景:基于不同项目组在一起编写自动化脚本,每个项目组都会有自己的环境配置,每个项目下都会有自己单独的实例化 ini 文件,觉得如果单独抽出来会整体看起来更优雅些;
优化前:
每个目录下都会有个 config.ini 文件,和对应实例化的一个脚本
def getEnv(env):
"""
获取环境配置项
:param env:
:return: {}
"""
config = configparser.ConfigParser()
path=os.path.join(os.path.dirname(__file__), 'config.ini')
config.read(path)
host = config[env]['host']
appkey = config[env]['appkey']
secret = config[env]['secret']
dbhost = config[env]['dbhost']
port = config[env]['port']
password = config[env]['password']
database = config[env]['database']
user = config[env]['user']
mock_url = config[env]['mock_url']
mock_username = config[env]['mock_username']
mock_password = config[env]['mock_password']
envdic={'host':host,'appkey':appkey,'secret':secret,'dbhost':dbhost,'port':port,'password':password,'database':database,'user':user,'mock_url':mock_url,'mock_username':mock_username,'mock_password':mock_password}
return envdic
if __name__ == '__main__':
host = getEnv('local')['host']
优化后,每个项目目录下有个 config.ini 文件,在获取 config 中参数时,只需要调用公共方法即可
from src.untils.envDict import EnvDict
if __name__ == '__main__':
host = EnvDict(env).host
公共映射 config.ini 文件如下
class EnvDict(object):
def __init__(self,env):
self.config = configparser.ConfigParser()
# 获取调用方文件目录下config.ini文件路径
self.path=os.path.join(os.path.dirname(inspect.getmodule(inspect.stack()[1][0]).__file__), 'config.ini')
self.config.read(self.path)
self.env = env
self._setAttr()
def _setAttr(self):
"""
将ini文件变量映射到envdict属性中
"""
for arg in self.config[self.env].keys():
setattr(EnvDict,arg,self.config[self.env][arg])