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

问题描述 投票:0回答:1

我正在尝试将标识光场景ID和本地存储文件的字典的数据发送到Autodesk Recap API。如果我仅发送数据,则响应中将包含正确的光场景ID。如果我包含文件(使用读取的二进制选项),则请求不会发布任何数据,并且API无法识别光场景。我已经使用Python请求成功创建了一个Photocene,并使用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)
python python-requests http-post autodesk-forge
1个回答
0
投票

如果使用文件,请求会自动添加'multipart / form-data',如果您手动设置'multipart / form-data',它也会设置'边界',还必须设置'边界',因此将其留给请求:] >

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"
}
...
© www.soinside.com 2019 - 2024. All rights reserved.