从NodeJS移植到Python3:如何发送含图片与文本的MultipartForm请求?
Python 3实现Multipart POST请求(对应你的NodeJS代码)
我帮你把NodeJS里发送包含图片和文本的multipart POST请求的逻辑,转换成Python 3的实现,分两种常用方案说明:
方案一:使用requests库(推荐,更简洁)
requests库对multipart/form-data的处理非常友好,不需要手动拼接复杂的请求体。
首先如果还没安装requests,先执行:
pip install requests
然后是代码实现:
import requests import json # 替换成你的实际参数 file_path = "xxx.jpeg" text = "xxx" # 先实现你NodeJS里的RequestData函数逻辑,这里假设它返回一个字典 def request_data(text_input): # 把NodeJS里this.RequestData的逻辑转成Python代码 return {"content": text_input} # 构造multipart请求的各个部分 multipart_parts = [ # 图片文件部分:对应NodeJS里的第一个multipart项 ("file", (file_path, open(file_path, "rb"), "image/jpeg")), # 文本内容部分:对应NodeJS里的第二个multipart项,指定Content-Type为text/plain ("text_content", (None, json.dumps(request_data(text)), "text/plain")) ] # 替换成你的自定义headers,注意不要加Content-Type,requests会自动处理 custom_headers = { "Authorization": "Your-Token-Here", # ...其他需要的请求头 } # 发送请求 response = requests.post( url="http://xxx", files=multipart_parts, headers=custom_headers ) # 处理响应 print(f"响应状态码:{response.status_code}") print(f"响应内容:{response.text}")
关键对应说明:
- NodeJS里的
fs.createReadStream(filePath)对应Python里的open(file_path, 'rb'),requests会自动处理文件流的读取 - NodeJS里的
JSON.stringify(this.RequestData(text))对应json.dumps(request_data(text)),你需要把NodeJS中RequestData的逻辑转成Python函数 - 图片部分的
Content-Disposition和Content-Type都通过元组参数指定,和NodeJS的配置完全对应 - 不要手动设置
Content-Type: multipart/form-data,requests会自动生成正确的boundary并填充这个请求头
方案二:使用urllib3库(你查阅的官方库)
如果你坚持用urllib3,需要手动构造multipart的每个字段并编码,代码会繁琐一些:
import urllib3 import json from urllib3.fields import RequestField from urllib3.filepost import encode_multipart_formdata # 替换成你的实际参数 file_path = "xxx.jpeg" text = "xxx" # 实现RequestData逻辑 def request_data(text_input): return {"content": text_input} # 初始化urllib3的连接池 http = urllib3.PoolManager() # 构造图片字段 image_field = RequestField( name="file", data=open(file_path, "rb").read(), filename=file_path, headers={"Content-Type": "image/jpeg"} ) # 构造文本字段 text_content = json.dumps(request_data(text)) text_field = RequestField( name="text_content", data=text_content, headers={"Content-Type": "text/plain"} ) # 编码multipart数据,得到请求体和Content-Type multipart_body, content_type = encode_multipart_formdata([image_field, text_field]) # 自定义headers,这里需要手动设置Content-Type custom_headers = { "Content-Type": content_type, "Authorization": "Your-Token-Here", # ...其他请求头 } # 发送请求 response = http.request( method="POST", url="http://xxx", body=multipart_body, headers=custom_headers ) # 处理响应 print(f"响应状态码:{response.status}") print(f"响应内容:{response.data.decode('utf-8')}")
注意事项:
- 确认文本部分的字段名(比如示例中的
text_content)和服务端期望的一致,NodeJS代码里第二个multipart项没写Content-Disposition的name,你需要根据服务端的接收逻辑调整 - 读取文件时一定要用二进制模式
rb,避免编码错误 - 如果
RequestData有复杂的逻辑,务必完整转换成Python代码,保证序列化后的JSON和NodeJS版本一致
内容的提问来源于stack exchange,提问作者Maiko Ohkawa
相关产品推荐
相关产品推荐

