简体   繁体   English

python请求api-具有文件和表单数据的http multipart帖子

[英]python requests api - http multipart post with file and form-data

Using requests 2.4.3. 使用请求2.4.3。 I want to post a file and send a few fields from a form to my flask server. 我想发布一个文件,并将一些字段从表单发送到我的Flask服务器。 I already have an angular app that validates flask is working btw. 我已经有一个角度应用程序来验证flask是否正常工作。

Based on various threads on the subject I've tried a few approaches to no avail. 基于该主题的各种线索,我尝试了几种方法都无济于事。 Here's what I've tried and the output: 这是我尝试过的内容和输出:

a) Putting everything in the files map 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) Separately pass data and files to the post API data = {'formfoo': 'whatever'} files = {'test.csv': open(fpath, 'rb')} resp = super(Session, self).post(url, data=data, files=files, verify=False, headers=multipart) 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) Separately pass data and files to the post API. c)分别将数据和文件传递到post API。 json.dumps the data dictionary like a usual post. json.dump数据字典就像通常的帖子一样。 data = {'formfoo': 'whatever'} files = {'test.csv': open(fpath, 'rb')} resp = super(Session, self).post(url, data=json.dumps(data), files=files, verify=False, headers=multipart) 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: Data must not be a string ValueError:数据不能为字符串

Either way the form data is not received by the server because the client encoding fails. 无论哪种方式,服务器都不会接收表单数据,因为客户端编码失败。 Any suggestions? 有什么建议么?

requests/2.4.3 works as expected: 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())

Request 请求

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--

Output 输出量

{'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM