通过配置文件获取通用配置

实用场景:

在实际工作中,有预发环境,有线上环境,url地址不一样,如果每次改代码非常麻烦,这时候就需要一个init的配置文件,来解决。
在Util下创建文件handle_init.py文件

##coding:utf-8
import openpyxl
import sys,os
import unittest
import configparser
base_path = os.getcwd()
new_base_pash = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))


class HandlerInit():
    def load_ini(self):
        file_path = new_base_pash + "/Config/server.ini"
        cf = configparser.ConfigParser()
        cf.read(file_path,encoding="utf-8-sig")
        return cf

    def get_value(self,key,section = None):
        """
        获取ini文件的value
        """
        if section == None:
            section = "server"
        cf = self.load_ini()
        try :
           data = cf.get(section,key)
        except Exception:
            print("没有获取到值")
            data = None
        return data

if __name__ == '__main__':
    hi = HandlerInit()
    print(hi.get_value("password"))

在Config下常见server.init文件,文件内容如下,随意编写。

[server]
host = http://www.imooc.com/
username = Mushishi
password = 密码
is_run = 3
import configparser
from tool import project_path

class ReadConfig:
    @staticmethod
    def get_config(file_path,section,option):
        cf = configparser.ConfigParser()
        cf.read(file_path)
        return cf.get(section,option)

if __name__ == '__main__':
print(ReadConfig.get_config(project_path.case_config_path,'DB',"db_config"))
[MODE]
mode={"login":[],
              "python":[],
               "recharge":"all",
               "business":[],
                "invest":"all"}

[DB]
db_config = {
    "host":"localhost",
    "user":"root",
    "password":"Hello1234",
    "database":"ceshi"}

[CHECKLEAVEAMOUNT]
check_list=["recharge","invest","withdraw"]

你可能感兴趣的:(通过配置文件获取通用配置)