【问题标题】:How to prevent Python Requests from switching to multipart transfer when I upload a large file?上传大文件时如何防止 Python 请求切换到多部分传输?
【发布时间】:2020-07-21 01:26:48
【问题描述】:

我需要使用 Python 请求在远程服务器上上传一个大文件。显然,当我们使用files 参数时,请求会自动将内容类型切换为“multipart/form-data”:

import io
import requests
from pprint import pprint

r =requests.put('https://httpbin.org/anything/{anything}', 
                files={ 'filename': io.BytesIO(b'many many bytes')})
pprint(r.json())
{'args': {},
 'data': '',
 'files': {'filename': 'many many bytes'},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Content-Length': '163',
             'Content-Type': 'multipart/form-data; '
                             'boundary=f75a6ed22a9281aab1e6c7288ff34583',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.23.0',
             'X-Amzn-Trace-Id': 'Root=1-5e8de885-83470619f8a4a57e3351b868'},
 'json': None,
 'method': 'PUT',
 'origin': '80.67.177.9',
 'url': 'https://httpbin.org/anything/{anything}'}

很遗憾,我的服务器不理解这一点。有没有办法禁用该功能以恢复为纯 HTTP 上传?

FWIW,文件太大,无法放入主内存。

【问题讨论】:

  • 问题实际上不是来自您的代码。这都是关于httpbin.org 服务器端的。即使是小文件。服务器将返回 `multipart/form-data,检查 that
  • 不,@αԋɱҽԃαмєяιcαη。我还嗅探了网络,毫无疑问 Python Requests 将数据发送为multipart/form-data。另外,如果我使用data=而不是file=上传一个小文件,httpbin会确认这是一个普通的HTTP上传。
  • @αԋɱҽԃαмєяιcαη 在发布上述评论时,我突然想到:“如果我将文件作为data 参数传递会发生什么?” 你猜怎么着... ;)
  • 大声笑,刚刚要分享。

标签: python file-upload python-requests python-3.5 http-put


【解决方案1】:

Python 请求支持streaming upload。您所要做的就是在data= 参数中传递一个类似文件的对象,而不是在问题中显示的files= 参数中:

import io
import requests
from pprint import pprint

r =requests.put('https://httpbin.org/anything/{anything}',
                data=io.BytesIO(b'many many bytes'))
pprint(r.json())
{'args': {},
 'data': 'many many bytes',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Content-Length': '15',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.23.0',
             'X-Amzn-Trace-Id': 'Root=1-5e8df4cc-fb2b5fdd121ba761f97d959a'},
 'json': None,
 'method': 'PUT',
 'origin': '80.67.177.9',
 'url': 'https://httpbin.org/anything/{anything}'}

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2010-12-04
    • 2014-11-09
    • 2017-02-11
    • 2015-06-28
    • 2011-12-25
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    相关资源
    最近更新 更多