封裝需要用的工具類:
1、封裝讀取Excel的工具類,這里選用的是pandas:
import pandas as pd path = 'test.xlsx' sheet_name = 'test_data' class with_excel: #構造函數,調用類時就運行 def __init__(self, path=None, sheet_name=None): if path and sheet_name: self.path = path self.sheet_name = sheet_name else: self.path = 'test.xlsx' self.sheet_name = 'test_data' self.data = self.open_excel() #獲取表格數據 def open_excel(self): df = pd.read_excel(self.path, self.sheet_name) return df #獲取表中單元格行數 def get_lines(self): lines = self.data.shape[0]#獲取了最后一行的行數 return lines #獲取一個單元格的內容(獲取多行的內容) def get_cell_data(self, row, col): return self.data.iloc[row, col] #將表格數據轉字典 def to_dict(self): test_data = [] for i in self.data.index.values: # 獲取與表頭對應的字典數據 row_data = self.data.loc[i].to_dict() test_data.append(row_data) return test_data if __name__ == '__main__': aa = with_excel(path, sheet_name)
2、封裝處理json的工具類:
import json
class open_json:
def __init__(self, filename):
self.data = self.read_data(filename)
#打開json文件
def read_data(self, filename):
with open(filename) as fp:
data = json.load(fp)
return data
#獲取對應的json數據
def get_data(self, data_id):
return self.data[data_id]
3、封裝mock方法
import mock
#使用mock模擬接口返回數據
def mock_test(mock_method, request_data, url, method, response_data):
mock_method = mock.Mock(return_value=response_data)
res = mock_method(url, method, request_data)
return res
4、封裝requests
import requests
import json
class RunMethod:
def post_main(self, url, data, header):
if header != None:
res = requests.post(url=url, data=data, headers=header)
else:
res = requests.post(url=url, data=data)
return res
def get_main(self, url, data, header):
if header !=None:
res = requests.get(url=url, data=data, headers=header)
else:
res = requests.get(url=url, data=data)
return res
def run_main(self, method, url, data=None, header=None):
if method == 'post':
res = self.post_main(url, data, header)
else:
res = self.get_main(url, data, header)
return json.dumps(res, ensure_ascii=False, sort_keys=True, indent=4)
