requests库调用post方法文件上传接口
直接上代码
import requests
import os
import jsonpath as jsonpath
import re
class TestFileUpload:
# 类变量
url = "http://myurl/TraceCodes/ImportTraceCodes"
PostType = "JP小包平邮"
PostCode = "JPPY"
# 定义文件路径的类变量
FilePath = {
"filename": ("跟踪号设置模版.csv", open(r"E:\testFileUpload\跟踪号设置模版.csv", "rb"), "text/csv")
}
# 接收获取HTML页面返回值的类变量
re_test = ""
def upload_file(self):
file_data = {
"BarCodeType": TestFileUpload.PostCode,
"BarCodeName": TestFileUpload.PostType,
"TraceType": 1,
}
# 定义请求头
headers_data ={
"Cookie":"ASP.NET_SessionId=e5elylofo4fmdbdjmvoc3ugk; loginFailureCount=null; OALoginToken=B25A6A2A5872EABB0567A5C9BBEF5D53",
"Content-Type": "multipart/form-data; boundary=----WebKitFormBoundarywIrP1vyws1E88NLl"
}
# 调用文件上传接口
res = requests.post(url=TestFileUpload.url, headers=headers_data, json=file_data, files=TestFileUpload.FilePath)
print(res.status_code)
# 打印输出返回值
print(res.text)
# 正则提取HTML页面返回值
TestFileUpload.re_test = re.search('<meta http-equiv="Content-Type" content="(.*?);', res.text).group(1)
print(TestFileUpload.re_test)
if __name__ == '__main__':
TestFileUpload().upload_file()