【问题标题】:python requests strips form data when content type is multipart/form-data?当内容类型为多部分/表单数据时,python 请求会剥离表单数据?
【发布时间】:2017-08-05 02:19:50
【问题描述】:

我正在尝试使用 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'
}

我在这里做错了什么?

【问题讨论】:

  • 对不起Coldspeed,我以为我确实提供了代码,是不是缺少什么? cURL 和 requests.post 有吗?
  • 对不起,我没有看到请求代码。
  • 尝试在您的请求代码中添加另一个标头:"User-Agent": "curl/7.47.1"
  • 如果您不发布任何文件,为什么要在标题中添加multipart

标签: python curl python-requests


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 1970-01-01
    • 2012-11-27
    • 2016-12-17
    • 2012-03-16
    • 2016-11-11
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多