用Python的requests库作接口测试——上传文件

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>"  
  },  
  ...  
}  

流式上传

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

with open('massive-body') as f:  
    requests.post('http://some.url/streamed', data=f)  
原文地址:https://www.cnblogs.com/dancesir/p/7550103.html