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. 查詢mysql數據庫中指定表指定日期的數據?有詳細2. mysql - 怎么生成這個sql表?3. mysql儲存json錯誤4. php - 公眾號文章底部的小程序二維碼如何統計?5. mysql - 表名稱前綴到底有啥用?6. mysql - 數據庫表中,兩個表互為外鍵參考如何解決7. Navicat for mysql 中以json格式儲存的數據存在大量反斜杠,如何去除?8. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現存在即更新應該使用哪個標簽?9. mysql - 數據庫建字段,默認值空和empty string有什么區別 11010. sql語句 - 如何在mysql中批量添加用戶?
