【问题标题】:Send data and files to Forge API using Python requests使用 Python 请求将数据和文件发送到 Forge API
【发布时间】:2020-04-08 05:14:53
【问题描述】:

我正在尝试将标识照片场景 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)

【问题讨论】:

    标签: python python-requests http-post autodesk-forge


    【解决方案1】:

    如果您使用文件,请求会自动添加“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"
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 2021-07-30
      • 1970-01-01
      • 2019-12-13
      • 2013-11-23
      相关资源
      最近更新 更多