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

Python解析Webhook POST请求:如何提取字典中特定字段值?

解决Flask Webhook提取JSON字段的问题

问题分析

你已经通过request.json拿到了请求字典,能打印Dic.keys()但无法提取特定字段,大概率是键名不匹配或者访问方式有误,先从基础排查:

排查与解决步骤

  • 第一步:确认键名完全一致
    先看Dic.keys()的实际输出,确保和你预期的"description"、"details"等键完全匹配(注意大小写、空格、特殊字符)。比如如果请求里的键是Description(首字母大写),用小写访问就取不到值。

  • 第二步:正确提取字段值
    直接用字典的键访问即可,推荐用get()方法,避免字段不存在时抛出异常:

    # 提取字段,字段不存在时返回None
    description = Dic.get("description")
    details = Dic.get("details")
    map_code = Dic.get("map_code")
    cross_street = Dic.get("cross_street")
    
    # 打印验证提取结果
    print(f"描述内容: {description}")
    print(f"详情内容: {details}")
    

    如果确定字段一定存在,也可以直接用Dic["description"],但这种方式在字段缺失时会触发KeyError,需要额外处理。

  • 第三步:添加异常处理(可选但推荐)
    为了避免非JSON请求或字段缺失导致服务崩溃,添加基础的异常捕获:

    @app.route('/my_webhook', methods=['POST'])
    def return_response():
        try:
            Dic = request.json
            if not Dic:
                print("请求不是有效的JSON格式")
                return Response(status=400)
    
            # 提取字段
            description = Dic.get("description")
            details = Dic.get("details")
    
            print(f"收到的描述: {description}")
            print(f"收到的详情: {details}")
    
            song = AudioSegment.from_wav('alert.wav')
            play(song)
    
            return Response(status=200)
        except Exception as e:
            print(f"处理请求出错: {str(e)}")
            return Response(status=500)
    

完整修改后的代码

from pydub import AudioSegment
from pydub.playback import play
from flask import Flask, request, Response
import json

app = Flask(__name__)

@app.route('/my_webhook', methods=['POST'])
def return_response():
    try:
        Dic = request.json
        if not Dic:
            print("无效的JSON请求")
            return Response(status=400)
        
        # 提取指定字段
        description = Dic.get("description")
        details = Dic.get("details")
        map_code = Dic.get("map_code")
        cross_street = Dic.get("cross_street")

        # 打印验证提取结果
        print(f"请求中的键列表: {list(Dic.keys())}")
        print(f"描述内容: {description}")
        print(f"详情内容: {details}")

        song = AudioSegment.from_wav('alert.wav')
        play(song)

        return Response(status=200)
    except Exception as e:
        print(f"错误信息: {str(e)}")
        return Response(status=500)

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:45:16