Python生成multipart请求数据
问题
最近产品中有个接口就是需要在请求中包含json和图片信息,也就是multipart/form形式的请求数据,但是在Python中如何生成这种请求数据呢?
本来构思的将不同段的数据全部取出,自己手动拼装,然后加入自定义头;可以仔细思考了一下,觉得自己造轮子肯定是重复的,Python应该有自带方法的;
结果
使用了requests库中的post方法的files参数,改参数支持元组形式,检测到改参数为元组自动将请求改为多段请求,每段请求中也支持用户自定义头部数据;
其中files参数的格式如下:
file = {'name': ('filename', data, 'content_type', headers)}
其中name、filename、content_type为String类型,data为二进制数据,heads为元组,包含你需要添加的头;
具体请求代码如下:
import requests, json, os
from requests.auth import HTTPDigestAuth
http_usr = "admin"
http_pwd = "admin"
add_face='''{ "faceLibType": "blackFD", "FDID": "1", "FPID": "8888", "name": "test", "bornTime": "2000-01-01" }'''
face_pic_path="./test_face.jpg"
face_mach_host = "http://192.168.8.20:80"
add_face_uri = "/FaceDataRecord"
fsize = os.path.getsize(face_pic_path)
head1={ 'Content-Length': len(add_face)}
head2={ 'Content-Length': fsize}
file = { 'FaceDataRecord': (None, add_face, 'application/json', head1), 'FaceImage': (None, open('test_face.jpg', 'rb'), 'image/jpeg', head2)}
target_url = face_mach_host + add_face_uri #需要多段数据的url
r = requests.post(target_url, files=file, auth = HTTPDigestAuth(http_usr, http_pwd))
print(r.text)
参考文章:
- How to send a “multipart/form-data” with requests in python?
- POST a Multipart-Encoded File
- Constructing multipart MIME messages for sending emails in Python
还没有评论,来说两句吧...