requests庫入門12-文件上傳和下載

由於找不到能夠演示上傳接口,因此只能純代碼了python

 

文件上傳api

上傳文件是在請求中使用files參數,files須要指向一個dict,而後dict裏面的鍵是接口中對應文件名的字段,而值就是打開這個文件讀取到內存的內容ide

以上圖中這個字段舉例post

path = 文件路徑url

file = {'templateFile':open(path.'rb')}spa

通常上傳文件是post請求3d

r = requests.post(url,files = file)code

 

 

文件下載blog

默認狀況下,使用requests庫在進行請求,響應體是會被當即下載的,因此須要使用stream這個參數覆蓋這個行爲,而後content來下載這個被推遲的響應體,若是不使用stream參數,是下載不到東西,確定是空的接口

r = requests.get(url,stream = True) path = 文件保存路徑 with open(path,'wb) as f:
 f.write(r.content)

 

咱們如今如下載圖片來作個示例,就以requests最新的logo

對着requests官方中文api文檔左邊的logo右鍵,複製圖片地址

地址是這個:http://docs.python-requests.org/zh_CN/latest/_static/requests-sidebar.png

import requests url = 'http://docs.python-requests.org/zh_CN/latest/_static/requests-sidebar.png' path = 'C:/Users/ms/Downloads/test.jpg' r = requests.get(url,stream = True) print(r.status_code) with open(path,'wb') as f: f.write(r.content)

path是存放路徑,請換成本身想要存放的路徑

能夠看到文件夾中有代碼中下載下來的test.jpg

打開看下,確實是requests的logo

相關文章
相關標籤/搜索