You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python requests向Flask API发送音频和文本时出现400错误,Postman测试正常

问题排查与解决方案

核心问题根源

  • 当请求包含文件上传(multipart/form-data格式)时,无法同时传递JSON payload,你客户端把text放在json参数中、服务端同时尝试读取JSON和表单字段的写法完全不匹配
  • 你后端代码里request.get_json()不仅完全没用到,还会因为请求格式不匹配产生隐性错误
  • 客户端没有把text字段放到表单数据中,导致后端request.form['text']读取不到对应字段,直接返回400错误

修复步骤

1. 修改Python请求端代码

把json=d改成data=d,将text字段放到表单数据中传输:

import requests
url= 'http://192.168.100.14:8000/v1/translate'
with open('/home/faizi/ai-chatbot-with-voice-driven-facial-animation/01_smalltalk_bot/game.wav', 'rb') as file:
    files = {'input_file': file}
    d = {"text":"hello, my name is faizan"}    
    req = requests.post(url, files=files, data=d)
    print(req.status_code)
    print(req.text)

2. 修改Flask服务端代码

删除无用的request.get_json()行,可选增加参数存在性判断避免报错:

from flask import Flask
from flask_cors import cross_origin
from flask import request, send_file
from Voice_Cloning_Module import demo_cli

app = Flask("foo")

@app.route('/v1/translate', methods=['POST', 'OPTIONS'])
@cross_origin()
def translate_mbart():
  # 删掉原来的request.get_json()无用代码
  if 'input_file' not in request.files:
      return "缺少音频文件", 400
  audio_file = request.files['input_file']
  audio_file.save("./bufferaudiofile/"+audio_file.filename)
  text = request.form.get('text')
  if not text:
      return "缺少text参数", 400
  returnedfile = demo_cli.clone(text,"./bufferaudiofile/"+audio_file.filename)
  path_to_clonefile = returnedfile
  return send_file(
    path_to_clonefile,
    mimetype="audio/wav",
    as_attachment=True,
    # flask新版本attachment_filename已弃用,旧版本可改回原字段名
    download_name="test.wav")

if __name__ == '__main__':
   app.run(host='0.0.0.0', port=8000)

可选排查技巧

如果还有问题可以在接口入口添加调试日志,确认接收到的参数:

print("请求类型:", request.content_type)
print("接收到的表单字段:", list(request.form.keys()))
print("接收到的文件:", list(request.files.keys()))

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:51:02