我需要执行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和文件
发布评论