Python请求:在单个请求中发布JSON和文件

编程入门 行业动态 更新时间:2024-10-14 14:20:55
本文介绍了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和文件

本文发布于:2023-11-17 08:51:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609520.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   Python   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!