向Python请求发出卷曲命令-不起作用

时间:2019-07-10 09:49:15

标签: python python-requests

我正在尝试将以下curl(效果很好)转换为Python代码:

curl -X POST https://api.example.com/c \
-H 'Authorization: Bearer {token}' \
-H 'content-type: multipart/form-data' \
-F 'attachment[c_id]=1111' \
-F 'attachment[file]=@file.png'

我尝试了两种不同的选择:

选项1:

import requests

headers = {
    'Authorization': 'Bearer {token}',
    'content-type': 'multipart/form-data',
}

files = {
    'attachment[c_id]': (None, '1111'),
    'attachment[file]': ('file.png', open('file.png', 'rb')),
}

response = requests.post('https://api.example.com/c',
                         headers=headers, files=files)

选项2:

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

headers = {
    'Authorization': 'Bearer {token}',
    'content-type': 'multipart/form-data',
}

multipart_data = MultipartEncoder(
    fields=(
        ('attachment[file]', open('file.png', 'rb')),
        ('attachment[c_id]', '1111')
    ))

response = requests.post('https://api.example.com/c',
                         headers=headers, data=multipart_data)

两个选项均失败,并出现以下错误:

requests.exceptions.ConnectionError: ('Connection aborted.', BrokenPipeError(32, 'Broken pipe'))

因此,这意味着Python代码以不同的方式工作,因为curl可以正常工作。

我尝试过https://curl.trillworks.com/-不幸的是,它没有帮助。 如何在Python上做同样的事情?

1 个答案:

答案 0 :(得分:1)

我刚刚找到了解决方案-问题出在Content-Type标头中。

重要提示::当我们使用“ files”参数进行请求时,我们不应使用Content-Type标头,请求会自行设置(有效负载的大小应在此范围内)标头,并且请求库将自动添加此信息。

以下代码可以正常工作:

import requests

headers = {
    'Authorization': 'Bearer {token}',
}

files = (
    ('attachment[c_id]', (None, '1111')),
    ('attachment[file]', ('file.png', open('file.png', 'rb')))
)

response = requests.post('https://api.example.com/c',
                         headers=headers, files=files)
相关问题