python - 无法使用 python requests 发布文件 - 来自curl的翻译

标签 python curl python-requests

以下命令有效,但我无法使用 python-requests (2.18.4) 重现它:

curl -X POST -H "Authorization: Bearer ..." \
             -H "Content-Type: multipart/form-data" \
             -F 'metadata={...} 
             -F 'data=@data.bz2;type=application/octet-stream' 
              https://www....com

使用下面的 send_devices,我收到“不支持的媒体类型”

def send_devices(basic_auth):
    endpoint_api = ' https://www....com'
    with open('data.bz2','rb') as payload:
        response = requests.post(endpoint_api, data={'metadata': ...,
                                                     'data': payload},
                                 headers={'Authorization': 'Bearer {0}'.format(basic_auth})

经过一些评论,我也尝试了,现在的错误是“无效的元数据 Json 字符串”:

def send_devices(basic_auth):
    endpoint_api = ' https://www....com'
    files = {'file': ('data.bz2', open('data.bz2', 'rb'), 'application/octet-stream')}
    response = requests.post(endpoint_api, data={"metadata": {"extensions":{"urnType":"IDFA"}}},
                             files=files, headers={'Authorization': 'Bearer {0}'.format(basic_auth)})

最佳答案

在第一个示例中,缺少文件类型

'data': ('data.bz2', open('data.bz2', 'rb'), 'application/octet-stream'),

在第二个示例中,有必要在同一文件字典上添加额外的发布数据。即使不是字典:

'metadata': ('metadata.csv', json.dumps({"extensions": ...}))}

解决办法:

def send_devices(basic_auth):
    endpoint_api = ' https://www....com'
    files = {'data': ('data.bz2', open('data.bz2', 'rb'), 'application/octet-stream'),
            'metadata': ('metadata.csv', json.dumps({"extensions": ...}))}
    response = requests.post(endpoint_api, files=files,
                             headers={'Authorization': 'Bearer {0}'.format(basic_auth)})

关于python - 无法使用 python requests 发布文件 - 来自curl的翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009287/

相关文章:

python - 索引错误 : list index out of range python 2. 7

python - 如何适应文档?

go - Curl 因这个 swagger 规范而失败

python - 使用 Postman 与请求发布到 Flask 会填充不同的请求属性

php - 似乎无法使用 php Guzzle 上传大文件

git - 无法 curl git 标签

python - 如何使 Python 请求包的响应成为 "file-like object"

python - Pygame-transform.rotate 结果使用大量 RAM

python : group by columns with columns values that are grouped by occurs only once and retain all other columns

python - 使用 Python 进行 MySQL 查询不返回所有结果