curl - Python request 上傳文件
問題描述
我嘗試用 curl 提交成功
curl --form file=@/home/test/sample.png --form username=test@noreply.com --form password=test --insecure --form lang[0]=cn --form lang[1]=jp --form langs[2]=en https://www.example.com/api
但我用 requests 嘗試了以下方法,卻得不到正確結果。請問正確的應該怎么寫?
data = { ’file’: open(’/home/test/test.png’,’rb’), ’username’: ’test@noreply.com’, ’password’: ’test’, ’lang[0]’: ’cn’, ’lang[1]’: ’jp’, ’lang[2]’: ’en’}r = requests.post(’https://www.example.com/api’, data=data, verify=False)
file = { ’file’: open(’/home/test/test.png’,’rb’) }data = { ’username’: ’test@noreply.com’, ’password’: ’test’, ’lang[0]’: ’cn’, ’lang[1]’: ’jp’, ’lang[2]’: ’en’}r = requests.post(’https://www.example.com/api’, data=data, files=file, verify=False)
另外我用 httpbin 測試,curl代碼 和 第二段代碼發出的請求是一樣的,但是 Python 得不到返回的 ID.
問題解答
回答1:files = {’file’: open(’test.png’, ’rb’)}requests.post(url, files=files)
參考 http://www.python-requests.or...
http://www.python-requests.or...
回答2:with open(’filename1’, ’rb’) as f1, open(’filename2’, ’rb’) as f2: files_to_upload = {’filename1’: f1,’filename2’: f2, }response = requests.post(url, files=files_to_upload)
相關文章:
1. Span標簽2. docker-machine添加一個已有的docker主機問題3. redis啟動有問題?4. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””5. docker-compose中volumes的問題6. android新手一枚,android使用httclient獲取服務器端數據失敗,但是用java工程運行就可以成功獲取。7. javascript - ng-options 設置默認選項,不是設置第一個哦,看清楚了!8. angular.js使用$resource服務把數據存入mongodb的問題。9. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?10. css - 求推薦適用于vue2的框架 像bootstrap這種類型的
