使用Python请求向Forge API发送数据和文件

使用Python请求向Forge API发送数据和文件,python,python-requests,http-post,autodesk-forge,Python,Python Requests,Http Post,Autodesk Forge,我正在尝试将识别photoscene ID的数据和本地存储文件的字典发送到Autodesk Recap API。如果我只发送数据,则响应包含正确的photoscene ID。如果我包含文件(使用读取二进制选项),则请求不会发布任何数据,API无法识别photoscene。我已经成功地创建了一个带有Python请求的photoscene,并用curl上传了图像,但我更愿意在一个Python函数中完成这一切 headers = { 'Authorization': 'Bearer {}'.f

我正在尝试将识别photoscene ID的数据和本地存储文件的字典发送到Autodesk Recap API。如果我只发送数据,则响应包含正确的photoscene ID。如果我包含文件(使用读取二进制选项),则请求不会发布任何数据,API无法识别photoscene。我已经成功地创建了一个带有Python请求的photoscene,并用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"
}
...
如果手动设置“内容类型”:“多部分/表单数据”,则不会设置边界:

...
{
    "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"
}
...