首先需要导入三个包。 openpyxl,操作excel文件 requests,发送Web网络请求 json,处理json对象
import openpyxl
import requests
import json
如果包不能用的话,需要先安装它,如
pip install openpyxl
定义几个变量
headers = {
'Content-Type': 'application/json',
'accept': 'text/plain'
}
file_excel = r'C:\Users\Zmrbak\Desktop\IP地址20220420.xlsx'
api_url = 'http://192.168.250.16/api/HostModels'
post 操作
def post_date(data):
rep = requests.post(url=api_url, data=json.dumps(data), headers=headers)
print(rep.status_code)
print(rep.text.encode(rep.encoding).decode('utf-8'))
处理空值
def default_data(data, default_=None):
if data is not None:
return data
else:
return default_
解析Excel文件
def load_excel(file_):
wb = openpyxl.load_workbook(file_)
sheet = wb['IP地址使用登记']
index = 0
for row in sheet.iter_rows():
index += 1
if index == 1:
continue
ip_inter = row[1].value
ip_public = row[2].value
host_name = row[3].value
host_mac = row[4].value
asset_number = row[5].value
location = row[6].value
usage = row[7].value
if ip_inter is None:
continue
input_data = {
"ipInAddress": "" + default_data(ip_inter, "") + "",
"ipInMacAddress": "" + default_data(host_mac, "") + "",
"ipOutAddress": "" + default_data(ip_public, "") + "",
"hostName": "" + default_data(host_name, "") + "",
"assetNumber": "" + default_data(asset_number, "") + "",
"location": "" + default_data(location, "") + "",
"usage": "" + default_data(usage, "") + "",
"holder": "赵庆明"
}
post_date(input_data)
Get 请求
def get_all_data():
rep = requests.get(api_url)
print(rep.text.encode(rep.encoding).decode('utf-8'))
执行程序
if __name__ == '__main__':
get_all_data()
print("done")
|