从excel中读数据
引入了xlrd包,读取excel中第一列内容,具体行数由代码中变量i和row控制
# 读取excel中第一列内容,保存为list
workbook = xlrd.open_workbook_xls('gggg.xls')
sheet = workbook.sheet_by_index(0)
i = 2 # 从第几行开始
row = 67 # 到第几行结束
i -= 1 # 为了与excel中的行数保持一致
idList = {}
while i < row:
val = sheet.cell(i, 0)
idList[i] = val.value
i = i + 1
print(idList)
发送get请求
request包来发送get请求,参数为url和headers
headers = {
'Authorization': "admin"
}
url1 = "http://localhost:8080/api/test/getInfo" + str(theId)
response = requests.get(url=url1, headers=headers)
print(response.text)
发送post请求
request包发送post请求,这里需要把从get请求获取的json数据新增一个键值对,因此用json包做一个转换,json.loads是把str转为dict类型,json.dumps是把dict转换为str类型。
headers2 = {
'Content-Type': 'application/json',
'Authorization': "admin"
}
text = response.text
tt = json.loads(text) # 把str类型转为dict类型
data = tt['data']
data['projectId'] = 1 # json新添加一个键值对
ttt = json.dumps(data) # 转为字符串类型
body = ttt.encode('utf8') # 编码设置为utf8
url2 = "https://localhost:8080/api/test/postInfo"
response2 = requests.post(url=url2, data=body, headers=headers2)
print(response2.text)
整体代码
import json
import time
import xlrd
from pip._vendor import requests
# 读取excel中第一列内容,保存为list
workbook = xlrd.open_workbook_xls('gggg.xls')
sheet = workbook.sheet_by_index(0)
i = 2 # 从第几行开始
row = 67 # 到第几行结束
i -= 1 # 为了与excel中的行数保持一致
idList = {}
while i < row:
val = sheet.cell(i, 0)
idList[i] = val.value
i = i + 1
print(idList)
# 遍历idList,发送get与post请求
headers = {
'Authorization': "admin"
}
headers2 = {
'Content-Type': 'application/json',
'Authorization': "admin"
}
for index in idList:
time.sleep(1) # 休眠1秒
theId = idList[index]
url1 = "http://localhost:8080/api/test/getInfo" + str(theId)
response = requests.get(url=url1, headers=headers)
print(response.text)
text = response.text
tt = json.loads(text) # 把str类型转为dict类型
data = tt['data']
data['projectId'] = 1 # json新添加一个键值对
ttt = json.dumps(data) # 转为字符串类型
body = ttt.encode('utf8') # 编码设置为utf8
url2 = "https://localhost:8080/api/test/postInfo"
response2 = requests.post(url=url2, data=body, headers=headers2)
print(response2.text)
print("全部插入完成,嘿嘿嘿")