一、配置文件格式
(1)一般配置文件使用ini文件
(2)内容格式:简单的思路如下
- Env是环境:通过读取配置文件获得当前的环境
- 根据当前的环境去读取环境下的具体信息:数据库、密钥、地址等等
[Env]
env = Test
[Test]
sheets_name = ["xxx", "xxx", "xxx", "xxx"]
secret_key = xxx
host = http://xxx.com
mysql_host = xxx.xxx.xxx.xxx
mysql_port = xxxx
mysql_user = xxx
mysql_password = xxx
mysql_db = xxx
[pre]
sheets_name = ["xxx", "xxx", "xxx", "xxx"]
secret_key = xxx
host = http://xxx.com
mysql_host = xxx.xxx.xxx.xxx
mysql_port = xxxx
mysql_user = xxx
mysql_password = xxx
mysql_db = xxx
二、config.ini文件的读取
具体见代码
# 导入的模块:了解configparser模块的功能
import os
import configparser
from basic import request
class ReadConfig:
@staticmethod
def get_data(key, value):
"""
key : 代表的是config文件中的[ xxx ]中的XXX
value:代表的是config文件中[ xxx ]下xxx = Test中的XXX
"""
# 获取config的路径(相对路径)
cur_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir)) # 根目录
config_path = os.path.join(cur_path, r"config\config.ini")
# 判断配置文件是否存在()
if os.path.exists(config_path) is True:
cf = configparser.ConfigParser()
cf.read(config_path, encoding='UTF-8')
return cf.get(key, value)
else:
print("file is not exist")
if __name__ == '__main__':
env = ReadConfig().get_data("Env", "env"))
env = ReadConfig().get_data(env , "host")) # 打印到http://xxx.com