python requests api - 带文件和表单数据的http多部分post

0 投票
1 回答
3364 浏览
提问于 2025-04-28 05:54

我在使用 requests 2.4.3 这个库,想把一个文件和一些表单字段发送到我的 Flask 服务器。顺便说一下,我已经有一个 Angular 应用程序可以验证 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 接口 data = {'formfoo': 'whatever'} files = {'test.csv': open(fpath, 'rb')} resp = super(Session, self).post(url, data=data, files=files, verify=False, headers=multipart)

    ## 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 接口。像平常的 POST 一样把数据字典用 json.dumps 转换一下。 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)

    ## 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: 数据不能是字符串

无论哪种方式,表单数据都没有被服务器接收到,因为客户端编码失败。有没有什么建议?

暂无标签

1 个回答

0

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}

撰写回答