封装前脚本:
with open(r"C:\Users\PycharmProjects\pythonProject6\other\20221025.png", "rb") as file:
# 请求体
data = MultipartEncoder(fields={"file": ("20221025.png", file, "image/png")})
# 请求地址
url = "http://xxx/api/varie/image/uploadPicture"
# 请求头
headers = {"apptoken": apptoken, "entId": "1", "postId": str(postId), "appId": str(appId),
"Content-Type": "multipart/form-data", "Accept": "application/json, text/plain, */*",
"Content-Length": "266849"}
# 因为Content-Type为multipart/form-data,会有multipart boundary,所以要更新请求头
headers.update({'Content-Type': data.content_type})
# params
params = {"imageType": "0", "sortId": "1"}
# 请求结果
response9 = requests.post(url=url, data=data, headers=headers, params=params)
r9 = response9.json()
print("new9:{}".format(r9))
封装后:
def upload_xlsx_file(self, method, url, files, data, headers):
headers = json.loads(Template(json.dumps(headers)).safe_substitute(**self.__argument))
filds = {"files": eval(files["files"])}
r = request(method=method, url=url, files=filds, data=data, headers=headers)
print(r.text)
数据分离
{
"method": "POST",
"url": "http://xxx/api/other/file/multifileUpload",
"files": {
"files": "('标.xlsx',open('./other/标.xlsx', 'rb'),'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')"
},
"data": {
"sheetType": "GOODS"
},
"headers": {
"apptoken": "$apptoken"
}
}
eval运用:
eval函数就是实现str转换成list、dict、tuple(而str函数实现把list 、dict、tuple转换成字符串)