![](/img/trans.png)
[英]GET request works with postman but not with python requests and curl
[英]file upload works with curl and postman but not python requests
我正在嘗試使用python請求庫將CSV文件上傳到API(該錯誤信息很少)。
(我正在運行Python 3.5,並在OS X 10.11.6上使用請求版本2.18.4)
終端中的curl命令可以正常工作: curl -F 'file=@/path/to/file.csv' myurl.com/upload -H "Authorization: TOKEN sometoken"
來自Postman的多部分/表單數據POST請求也可以使用,但是我似乎無法使其與python請求庫一起使用。
我已經嘗試了此請求的許多變體:
import requests
headers = {'Authorization': 'TOKEN sometoken', 'Content-Type': 'multipart/form-data'}
with open(file_path, 'rb') as f:
r = requests.post(myurl, headers=headers, data=f)
## I've also tried data={"file": f}
我得到的狀態碼為200,但響應為{"success": "false"}
(非常無助)。
與curl請求相比,我在python請求中缺少什么?
編輯: curl
命令的-F
標志似乎模擬了已提交的HTML表單...是否可以通過請求執行此操作?
在您的curl
代碼中,您使用-F
參數,該參數將數據作為多部分消息提交-換句話說,您正在上傳文件。
對於requests
您可以使用files
參數發布文件。 一個例子:
import requests
headers = {'Authorization': 'TOKEN sometoken'}
data = {'file': open(file_path, 'rb')}
r = requests.post(myurl, headers=headers, files=data)
請注意, requests
將根據提交的數據自動創建Content-Type標頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.