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

Flask API忽略elif与else语句,触发KeyError: shape错误

问题分析与解决

核心问题

  • 直接通过键索引(如request.json['shape'])访问嵌套JSON中不存在的键会抛出KeyError,导致代码无法进入后续分支
  • 调整分支顺序后仅顶部分支生效,说明后续分支的判断逻辑依然存在键访问问题,或条件覆盖范围有误

修复方案

1. 安全获取嵌套JSON字段

用字典的get()方法替代直接索引,避免因键不存在触发错误:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/process', methods=['POST'])
def process_json():
    data = request.json
    # 安全获取字段,不存在则返回None
    shape = data.get('shape')
    sphere_info = data.get('geometry', {}).get('sphere')
    
    if shape == 'cube':
        return jsonify({"status": "success", "action": "processed cube"})
    elif sphere_info is not None:
        return jsonify({"status": "success", "action": "processed sphere"})
    else:
        return jsonify({"status": "error", "message": "unsupported structure"})

2. 分支条件优化

若JSON结构存在不同嵌套层级,需先检查键是否存在再取值比较:

if 'shape' in data and data['shape'] == 'cube':
    # Cube处理逻辑
elif 'geometry' in data and 'sphere' in data['geometry']:
    # Sphere处理逻辑
else:
    # 默认处理逻辑

示例测试JSON

Cube请求JSON

{
    "shape": "cube",
    "size": 5
}

Sphere请求JSON

{
    "geometry": {
        "sphere": {
            "radius": 3
        }
    }
}

错误原因补充

之前触发KeyError: shape,是因为Sphere的JSON中不存在shape键,而第一个if分支直接通过data['shape']访问该键,导致代码在进入elif分支前就报错终止。改用安全取值方式即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:00:54