POST一个多部分编码(Multipart-Encoded)的文件

Requests使得上传多部分编码文件变得很简单:

    >>> url = 'http://httpbin.org/post'  
    >>> files = {'file': open('report.xls', 'rb')}  
      
    >>> r = requests.post(url, files=files)  
    >>> r.text  
    {  
      ...  
      "files": {  
        "file": "<censored...binary...data>"  
      },  
      ...  
    }  

你可以显式地设置文件名,文件类型和请求头:

    >>> url = 'http://httpbin.org/post'  
    >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}  
      
    >>> r = requests.post(url, files=files)  
    >>> r.text  
    {  
      ...  
      "files": {  
        "file": "<censored...binary...data>"  
      },  
      ...  
    }  

如果你想,你也可以发送作为文件来接收的字符串:

 

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "some,data,to,send\\nanother,row,to,send\\n"
  },
  ...
}

 

流式上传

Requests支持流式上传,这允许你发送大的数据流或文件而无需先把它们读入内存。要使用流式上传,仅需为你的请求体提供一个类文件对象即可:

    with open('massive-body') as f:  
        requests.post('http://some.url/streamed', data=f)  

 

 

另外:

Requests本身虽然提供了简单的方法POST多部分编码(Multipart-Encoded)的文件,但是Requests是先读取文件到内存中,然后再构造请求发送出去。

如果需要发送一个非常大的文件作为 multipart/form-data 请求时,为了避免把大文件读取到内存中,我们就希望将请求做成数据流。

默认requests是不支持的(或很困难), 这时需要用到第三方包requests-toolbelt

两个库POST多部分编码(Multipart-Encoded)的文件示例代码分别如下:

1. Requests库(先读取文件至内存中)

import requests
 
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
 
r = requests.post(url, files=files)
print r.text

2. Requests+requests-toolbelt库(直接发送数据流)

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
 
m = MultipartEncoder(
    fields={'field0': 'value', 'field1': 'value',
            'field2': ('upload.zip', open('upload.zip', 'rb'), 'application/zip')}
    )
 
r = requests.post('http://httpbin.org/post', data=m,
                  headers={'Content-Type': m.content_type})
print r.text

转自:http://lovesoo.org/requests-post-multiple-part-encoding-multipart-encoded-file-format.html

posted @ 2018-04-28 23:50  cc成  Views(3786)  Comments(0Edit  收藏  举报