python - 使用 Python 请求将数据和文件发送到 Forge API
问题描述
我正在尝试将标识照片场景 ID 的数据和本地存储文件的字典发送到 Autodesk Recap API。如果我只发送数据,则响应包含正确的照片场景 ID。如果我包含文件(使用读取二进制选项),则请求不会发布任何数据,并且 API 无法识别照片场景。我已经使用 Python 请求成功创建了一个照片场景,并使用 curl 上传了图像,但我更愿意在单个 Python 函数中完成所有这些工作。
headers = {
'Authorization': 'Bearer {}'.format(access_token),
'Content-Type': 'multipart/form-data'
}
data = {
'photosceneid': photoscene_id,
'type': 'image'
}
files = {}
img_dir = os.listdir('Recap/')
for img in img_dir:
files['file[{}]'.format(img_dir.index(img))] = open('Recap/' + img, 'rb')
post = requests.post(url='https://developer.api.autodesk.com/photo-to-3d/v1/file', headers=headers, data=data,
files=files)
解决方案
如果您使用文件,请求会自动添加“多部分/表单数据”,如果您手动设置“多部分/表单数据”,它还会设置“边界”,您还必须设置“边界”,因此将其留给请求:
import requests
import os
import json
headers = {
'Authorization': 'Bearer {}'.format("xxx")
}
data = {
'photosceneid': "xxx",
'type': 'image'
}
files = {}
img_dir = os.listdir('Recap/')
for img in img_dir:
files['file[{}]'.format(img_dir.index(img))] = open('Recap/' + img, 'rb')
post = requests.post(url='http://httpbin.org/post', headers=headers, data=data, files=files)
print(json.dumps(post.json(), indent=4, sort_keys=True))
请注意,输出设置了边界:
...
{
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Bearer xxx",
"Content-Length": "78299",
"Content-Type": "multipart/form-data; boundary=cd2f6bf5f67653c6e2c423a2d23c929a",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
}
...
如果您手动设置 'Content-Type': 'multipart/form-data',则不会设置边界:
...
{
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Bearer xxx",
"Content-Length": "78299",
"Content-Type": "multipart/form-data",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
}
...