当内容类型是multipart / form-data时,python请求剥离表单数据?

时间:2017-08-05 02:19:50

标签: python curl python-requests

我正在尝试使用Python请求复制下面的cURL命令,但似乎请求剥离表单数据,而不是按照我的预期添加正确的内容长度和边界信息。以下是详细信息:

curl -X POST -H "Authorization: Bearer xyzabc1234" -H "Cache-Control: no-cache" -H "Content-Type: multipart/form-data" -F "firstArgument=http://www.somewebsite.com/Images/pic.jpg" -F "secondArgument=YaddaYadda" http://httpbin.org/post

我正在尝试将请求发出为:

r = requests.post(url='http://httpbin.org/post', 
headers={
    'Authorization':'Bearer XYZ1233', 
    'Cache-Control':'no-cache', 
    'Content-Type':'multipart/form-data'}, 
data={
    'firstArg':'https://www.fakesiteyolo.com/Images/ok.jpg', 
    'secondArg':'YaddaYadda'})

使用cURL时,我得到的反应如下:

{
    "args": {},
    "data": "",
    "files": {},
    "form": {
    "firstArg": "YaddaYadda",
    "secondArg": "https://www.fakesiteyolo.com/Images/ok.jpg"
},
    "headers": {
    "Accept": "*/*",
    "Authorization": "Bearer ABC12345",
    "Cache-Control": "no-cache",
    "Connection": "close",
    "Content-Length": "320",
    "Content-Type": "multipart/form-data; boundary=------------------------2a19bf0d22dbe8a3",
    "Expect": "100-continue",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.47.1"
    },
    "json": null,
    "origin": "203.63.117.8",
    "url": "http://httpbin.org/post"
}

我们可以清楚地看到那里的表单数据,但是当我使用请求时,我得到了这个:

    {
    'args': {},
    'data': '',
    'files': {},
    'form': {},
    'headers': {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        'Authorization': 'Bearer XYZ1233',
        'Cache-Control': 'no-cache',
        'Connection': 'close',
        'Content-Length': '75',
        'Content-Type': 'multipart/form-data',
        'Host': 'httpbin.org',
        'User-Agent': 'python-requests/2.18.2'
    },
    'json': None,
    'origin': '203.63.117.8',
    'url': 'http://httpbin.org/post'
}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

所以这在某种程度上是Python请求的限制,我可以通过以下方式实现我想通过requests_toolbelt实现的目标:

http://toolbelt.readthedocs.io/en/latest/uploading-data.html#streaming-multipart-data-encoder