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

使用UrlRequest连接Flask后端与Kivy应用遇400错误请求被拒

Flask后端无法接收Kivy UrlRequest数据(400错误)排查与修复

问题根源

你的代码核心问题是请求的Content-Type头部与实际发送的数据格式不匹配:

  • Kivy中用urlencode()生成的是application/x-www-form-urlencoded格式的字符串,但你将Content-Type设为application/json
  • Flask的request.json只能解析JSON格式的请求体,无法识别表单格式数据,因此返回400错误

直接修复方案

修改Kivy代码(发送JSON格式数据)

导入json模块,将请求体转为JSON字符串,保持Content-Type与数据格式一致:

import json

def load_content(self, query):
    # 将参数转为JSON格式字符串
    req_body = json.dumps({'content': query})
    headers = {
        'Content-Type': 'application/json'
    }
    req = UrlRequest(
        'http://127.0.0.1:5000/recipes/ask_mobile',
        req_body=req_body,
        req_headers=headers,
        on_error=handle_error
    )
    print(req.req_body)

后端增加容错处理(可选但推荐)

避免直接读取request.json['content']导致的KeyError,同时明确返回错误信息:

@recipes_blueprint.route('/ask_mobile', methods=['POST'])
def ask_recipe_mobile():
    # 校验请求是否为JSON格式
    if not request.is_json:
        return jsonify({
            'status': 400,
            'message': '请求格式错误,需提交JSON数据'
        }), 400
    
    # 安全获取content字段
    content = request.json.get('content')
    if not content:
        return jsonify({
            'status': 400,
            'message': '请求缺少必填字段:content'
        }), 400
    
    print(content)
    recipe = recipe_request_mobile(content)
    return jsonify({
        'data': recipe,
        'status': 200,
        'message': 'Recipe created successfully'
    }), 200

通用排查步骤

  • 核对请求格式与Content-Type:始终保证发送的数据格式与Content-Type头部一致,JSON对应application/json,表单对应application/x-www-form-urlencoded
  • 查看Flask调试日志:启动Flask时开启debug=True(app.run(debug=True)),控制台会输出具体的400错误原因,直接定位问题
  • 用工具验证后端端点:使用curl或Postman直接向后端发请求,先确认端点功能正常,再调试Kivy代码。示例curl命令:
curl -X POST -H "Content-Type: application/json" -d '{"content": "测试查询"}' http://127.0.0.1:5000/recipes/ask_mobile
  • 打印请求错误详情:在Kivy的错误回调中输出响应状态码和内容,便于定位问题:
def handle_error(req, result):
    print(f"错误状态码:{req.resp_status}")
    print(f"错误响应内容:{result}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 05:53:10