标签:header 没有 http 输出 alt import 优化 python3.4 book
尝试写了一个简单的接口测试,基于Python3.4,主要用到了Python读取excel以及requests库的知识,也算是对这段时间Python基础知识学习的一个巩固吧。
因为还没有学习到Python中类、对象等相关知识,所以代码看起来很散,没有封装,也没有优化。如有问题,希望大家能帮忙指出。
import xlrd
import requests
#下文中将用到的全局变量
nrows = 0
rdict = {}
relist=[]
#从excel中导入数据
def imptestcase():
fname = ‘testcase.xlsx‘
bk = xlrd.open_workbook(fname)
try:
sheet = bk.sheet_by_name(‘case1‘)
except:
print("no sheet in %s named sheet1" %fname)
global nrows
nrows = sheet.nrows
ncols = sheet.ncols
for i in range(0,ncols):
data = sheet.col_values(i)
global rdict
rdict[data[0]]=data[1:]
#将excel读取的数据封装成请求,并发送
def sendpost():
#response = requests.post(url,json = data,headers = headers,verify=False)
for i in range(0,nrows-1):
url = rdict[‘url‘][i]
if rdict[‘headers‘][i]!=‘‘:
headers = eval(rdict[‘headers‘][i]) #str to dict
else:
headers = {}
if rdict[‘json‘][i]!=‘‘:
json = eval(rdict[‘json‘][i]) #str to dict
else:
json = {}
if rdict[‘params‘][i]!=‘‘:
params = eval(rdict[‘params‘][i]) #str to dict
else:
params = {}
try:
r = requests.get(url,json = json,headers = headers,params = params,verify=False)
r.raise_for_status()
r.encoding=r.apparent_encoding
global relist
relist.append(r.status_code)
except Exception as e:
print(e)
print(‘请求失败‘)
#把返回的结果输出到html中,形成HTML报告(知识简单的展示,没有样式)
def output_html():
fout=open(‘output.html‘,‘w‘,encoding=‘UTF-8‘, newline=‘‘)
fout.write(‘<html>‘)
fout.write(‘<head>‘)
fout.write(‘<meta charset = "UTF-8"/>‘)
fout.write(‘</head>‘)
fout.write(‘<body>‘)
fout.write(‘<h1>report<h1>‘)
fout.write(‘<table>‘)
fout.write(‘<tr>‘)
fout.write(‘<td>%s</td>‘ % relist)
fout.write(‘</tr>‘)
fout.write(‘</table>‘)
fout.write(‘</body>‘)
fout.write(‘</html>‘)
fout.close()
if __name__ == ‘__main__‘:
imptestcase()
sendpost()
output_html()
【excel内容】
标签:header 没有 http 输出 alt import 优化 python3.4 book
原文地址:http://www.cnblogs.com/wyfighting/p/zxpython.html