使用requests模块请求接口时,会遇到Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryQwiOKYyOtrkiQ1K3这个请求体的格式,我们可以借助第三方库MultipartEncoder进行处理
处理方式如下:
1:先安装MultipartEncoder:
pip install requests_toolbelt
2:先用postman进行请求,确认是否请求的通(未带file文件)
3:使用代码实现
import requests, json, random, string
from requests_toolbelt import MultipartEncoder
def send_resp():
dict = {"id": "",
"project_id": 8,
"title": "uums",
"tool": "gatling"
}
url = "https://sep.sensetime.com/perf/add"
body = MultipartEncoder(fields={"data": json.dumps(dict)},
boundary=''.join(random.sample(string.ascii_letters + string.digits, 30))
)
headers = {"token": "", # 填入token值
"Content-Type": body.content_type}
resp = requests.post(url, data=body, headers=headers)
print(resp.json())
4:先用postman进行请求,确认是否请求的通(带file文件)
5:代码实现:
import os
import requests, json, random, string
from requests_toolbelt import MultipartEncoder
def send_resp():
dict = {"id": "",
"project_id": 8,
"title": "uums",
"tool": "gatling"
}
url = "https://sep.sensetime.com/perf/add"
body = MultipartEncoder(fields={"data": json.dumps(dict), "file": os.path.join(os.path.abspath("./"),"1.jpg")},
boundary=''.join(random.sample(string.ascii_letters + string.digits, 30))
)
headers = {"token": "", # 填入token值
"Content-Type": body.content_type}
resp = requests.post(url, data=body, headers=headers)
print(resp.json())