python+requests+unittest接口自动化(6):config的使用和封装

configparser包的使用:

首先是config.ini,也就是configparser包可识别的文件格式和文件内容:

格式当然那就是以“.ini”为文件后缀;内容则是如下:

#filename = config.ini
[url]
urla = https://www.baidu.com
urlb = https://github.com

[detail]
name = tom
name = david

[url]和[detail]在包中被称作section,中文可以叫“节”,然后里面以键= 值的方式进行赋值。

详细解释可以到官网查看:https://docs.python.org/3/library/configparser.html

以下为读取config.ini文件的代码:

#总之先导入
import configparser
#实例化
cf = configparser.ConfirParser()
#传入文件路径,通过read读取文件
filepath = "文件路径“
content = cf.read(filepath)
#传入section和key来得到值
value = cf.get(section,key)
#如urla就是:
getUrl = cf.get("url","urla")

以下为写config.ini文件的代码:

import configparser

cf = configparser.ConfigParser()
cf.read(filepath)
#设置新的值
cf.set(section,key,value)
#以写的权限,打开文件
fp = open(filepath,"w")
#通过内置方法写入值
cf.write(fp)
#关闭文件
fp.close()

但实际使用中,我们会对configparse进行封装,方便调用:

import configparser


class ReadConfig(filepath):
    def __init__(self):
        self.cf=configparser.ConfigParser()
        self.cf.read(filepath)

    def get_value(self, section, key):
        value = self.cf.get(section,key)
        return value

    def set_value(self,section,key,value):
        self.cf.set(section,key,value)
        file = open(filepath,"w")
        self.cf.write(file)
        file.close()


猜你喜欢

转载自blog.csdn.net/pythonstud/article/details/85245927