Python请求:在单个请求中发布JSON和文件 [英] Python Requests: Post JSON and file in single request

查看:162
本文介绍了Python请求:在单个请求中发布JSON和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行API调用以上传文件以及包含有关文件详细信息的JSON字符串.

I need to do a API call to upload a file along with a JSON string with details about the file.

我正在尝试使用python请求库来做到这一点:

I am trying to use the python requests lib to do this:

import requests

info = {
    'var1' : 'this',
    'var2'  : 'that',
}

data = json.dumps({
    'token' : auth_token,
    'info'  : info,
})

headers = {'Content-type': 'multipart/form-data'}

files = {'document': open('file_name.pdf', 'rb')}

r = requests.post(url, files=files, data=data, headers=headers)

这将引发以下错误:

    raise ValueError("Data must not be a string.")
 ValueError: Data must not be a string

如果我从请求中删除文件",则该文件有效.
如果我从请求中删除数据",则该数据有效.
如果我不将数据编码为JSON,那么它将起作用.

If I remove the 'files' from the request, it works.
If I remove the 'data' from the request, it works.
If I do not encode data as JSON it works.

由于这个原因,我认为错误与在同一请求中发送JSON数据和文件有关.

For this reason I think the error is to do with sending JSON data and files in the same request.

关于如何使它工作的任何想法?

Any ideas on how to get this working?

推荐答案

请勿使用json进行编码.

Don't encode using json.

import requests

info = {
    'var1' : 'this',
    'var2'  : 'that',
}

data = {
    'token' : auth_token,
    'info'  : info,
}

headers = {'Content-type': 'multipart/form-data'}

files = {'document': open('file_name.pdf', 'rb')}

r = requests.post(url, files=files, data=data, headers=headers)

请注意,这不一定是您想要的,因为它将成为另一个表单数据部分.

Note that this may not necessarily be what you want, as it will become another form-data section.

这篇关于Python请求:在单个请求中发布JSON和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆