读取ini文件
- 安装
configparser
ini的格式如下
-
\]内为key值
- 配置文件不需要加引号
bash
[host]
api_sit_url = http://sellshop.5istudy.online/sell/shouji/query
read_ini()方法
- 主要作用是获取ini文件
- 写法比较固定,如下:
bash
import configparser
import os
path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),"config", "settings.ini")
def read_ini():
config = configparser.ConfigParser()
config.read(path, encoding="utf8")
return config
- 可以在测试用例中直接使用
合并 read_ini() 和 read_data() 方法
- 这两个方法都是读取操作,可以合并到一个文件中
- 如果一个文件中有两个方法都返回数据,那么可以将它们放到一个类中,代码如下:
bash
import configparser
import os
import yaml
ini_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "settings.ini")
data_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "data", "data.yaml")
class FileRead:
def __init__(self):
self.ini_path = ini_path
self.data_path = data_path
def read_ini(self):
config = configparser.ConfigParser()
config.read(self.ini_path, encoding="utf8")
return config
def read_data(self):
f = open(self.data_path, encoding="utf8")
data = yaml.safe_load(f)
return data
# 此处直接实例化,方便调用
get_data = FileRead()
- 测试用例中可以做相应修改