python发送multipart-form-data请求

写接口测试时,遇到这个问题,在网上看了很多文档都不太好用,自己总结了一下:

1.引包

1
from requests_toolbelt import MultipartEncoder

2.准备数据

1
2
3
4
5
6
7
8
9
10
11
12
13
cookie = get_token
url = ADD_IMAGE_TO_REPO_URL + REPO_ID + "/faces"
binary_file = ('123.jpg', open(image_path + "123.jpg", 'rb'), 'image/jpg')
arguments = json.dumps({
"image": "123.jpg"})
headers = {'Cookie': cookie}
headers['Content-Type'] = multipart_encoder.content_type
multipart_encoder = MultipartEncoder(
fields={
'binary_file': binary_file,
'arguments': arguments,
},
)

3.发送请求

1
2
response = requests.post(url, headers=headers,
data=multipart_encoder, verify=False)