![](/img/trans.png)
[英]Python Requests - Post a zip file with multipart/form-data
[英]python requests api - http multipart post with file and form-data
使用請求2.4.3。 我想發布一個文件,並將一些字段從表單發送到我的Flask服務器。 我已經有一個角度應用程序來驗證flask是否正常工作。
基於該主題的各種線索,我嘗試了幾種方法都無濟於事。 這是我嘗試過的內容和輸出:
a)將所有內容放入文件映射
data = {'formfoo': 'whatever'}
files = {'test.csv': open(fpath, 'rb'), 'data': json.dumps(data)}
resp = super(Session, self).post(url,
files=files,
verify=False,
headers=multipart)
## BRINGS THIS ERROR ###
File "../2.7/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
b)分別將數據和文件傳遞到post API數據= {'formfoo':'whatever'} files = {'test.csv':open(fpath,'rb')} resp = super(Session,self).post (URL,數據=數據,文件=文件,驗證=假,標題=多部分)
## BRINGS THIS ERROR. Same as (a) ###
File "../2.7/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
c)分別將數據和文件傳遞到post API。 json.dump數據字典就像通常的帖子一樣。 data = {'formfoo':'whatever'}文件= {'test.csv':open(fpath,'rb')} resp = super(Session,self).post(url,data = json.dumps(data) ,文件=文件,驗證= False,標頭=多部分)
## BRINGS THIS ERROR ###
File "./venv/lib/python2.7/site-packages/requests/models.py", line 114, in _encode_files
raise ValueError("Data must not be a string.")
ValueError:數據不能為字符串
無論哪種方式,服務器都不會接收表單數據,因為客戶端編碼失敗。 有什么建議么?
requests/2.4.3
可以正常工作:
#!/usr/bin/env python
import requests
response = requests.post('http://httpbin.org/post',
files={"file":open("file", "rb")},
params={'param':'param data'},
data={"data": "data data"})
response.raise_for_status()
print(response.json())
POST /post?param=param+data HTTP/1.1
Host: httpbin.org
Content-Length: 238
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate
User-Agent: python-requests/2.4.3
Content-Type: multipart/form-data; boundary=0f34a3cfc1b448e78ef2bef3176d8948
--0f34a3cfc1b448e78ef2bef3176d8948
Content-Disposition: form-data; name="data"
data data
--0f34a3cfc1b448e78ef2bef3176d8948
Content-Disposition: form-data; name="file"; filename="file"
data
--0f34a3cfc1b448e78ef2bef3176d8948--
{'files': {'file': 'data'},
'form': {'data': 'data data'},
'url': 'http://httpbin.org/post?param=param+data',
'args': {'param': 'param data'},
'data': '',
'headers': {'Content-Length': '238',
'Connection': 'close',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.4.3',
'X-Request-Id': '7afbf052-98f0-4e5e-8c6f-b16cfbfacbe9',
'Content-Type': 'multipart/form-data; boundary=0f34a3cfc1b448e78ef2...',
'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*'},
'json': None}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.