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

Azure Function App接收Webhook POST请求时出现500错误排查

Azure Function部署后POST请求返回500错误排查

问题描述

本地运行Azure Function时,向https://localhost:7071/api/blahpost发送POST请求可正常执行updateRT及后续逻辑;但部署到Azure云端后,相同请求返回500错误,日志仅显示已进入alert_name == "BlockMe"的判断并打印了客户端IP,却未执行updateRT.main()及后续代码。

请求Payload示例

{
"alert_type": "RATE_BASED_WITH_GROUPS",
"alert_name": "BlockMe",
"search_period": "300000",
"hit_oeprator": "GREATER_THAN",
"messages": "[{\"fields\":[{\"name\":\"msg\",\"content\":\"primary credentials rejected - invalid user\"},{\"name\":\"count\",\"content\":\"150\"},{\"name\":\"client_ip\",\"content\":\"178.18.193.158\"},{\"name\":\"username\",\"content\":\"stuff\"},{\"name\":\"status\",\"content\":\"reject\"}],\"Count\":150.0}]"
}

函数代码

import azure.functions as func
import logging
import updateRT
app = func.FunctionApp(auth_level=func.AuthLevel.FUNCTION)
@app.route(route="blahpost")
def blahpost(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        req_body = req.get_json()
    except ValueError:
        return func.HttpResponse(
             "Invalid JSON format",
             status_code=400
        )
    alert_name = req_body.get('alert_name')
    messages = req_body.get('messages')
    if alert_name == "BlockMe":
        logging.info(req_body)
        for item in messages['fields']:
            if item['name'] == 'client_ip':
                targetIP = item['content']
                logging.info(targetIP)
                response = updateRT.main(targetIP)
                logging.info(response)
                return func.HttpResponse(response, status_code=200)
    if alert_name == "USER-Lockout-Alert":
        logging.info(req_body)
        for item in messages['fields']:
            if item['name'] == 'username':
                username = item['content']
                logging.info(username)
    return func.HttpResponse("Function executed successfully.")

问题根源

不是路由配置问题——日志已显示进入alert_name判断分支,说明请求已正确到达函数。真正的问题在于:

  1. Payload中的messages字段是JSON字符串(被引号包裹的数组),而非直接的JSON对象。本地测试时可能误传入了解析后的对象,但云端接收的是原始字符串,执行messages['fields']时会抛出类型错误(字符串没有fields属性),导致500错误。
  2. 即使解析了字符串,messages是数组类型,直接遍历messages['fields']依然会报错,需要先取数组中的元素再访问fields。

修复方案

  1. 解析messages字符串为JSON对象:添加JSON解析逻辑,并处理解析失败的情况
  2. 修正数组遍历逻辑:针对messages的数组结构调整循环方式
  3. 确保依赖部署完整:确认updateRT模块及其他依赖已正确打包到部署包中

修改后的核心代码片段:

import azure.functions as func
import logging
import updateRT
import json  # 新增导入

app = func.FunctionApp(auth_level=func.AuthLevel.FUNCTION)
@app.route(route="blahpost")
def blahpost(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        req_body = req.get_json()
    except ValueError:
        return func.HttpResponse(
             "Invalid JSON format",
             status_code=400
        )
    alert_name = req_body.get('alert_name')
    messages = req_body.get('messages')
    
    # 新增:解析messages字符串为JSON对象
    try:
        messages = json.loads(messages)
    except json.JSONDecodeError:
        return func.HttpResponse("Invalid messages format", status_code=400)
    
    if alert_name == "BlockMe":
        logging.info(req_body)
        # 修正:先遍历messages数组中的元素,再访问fields
        for msg_item in messages:
            for item in msg_item['fields']:
                if item['name'] == 'client_ip':
                    targetIP = item['content']
                    logging.info(targetIP)
                    response = updateRT.main(targetIP)
                    logging.info(response)
                    return func.HttpResponse(response, status_code=200)
    if alert_name == "USER-Lockout-Alert":
        logging.info(req_body)
        # 同样修正遍历逻辑
        for msg_item in messages:
            for item in msg_item['fields']:
                if item['name'] == 'username':
                    username = item['content']
                    logging.info(username)
    return func.HttpResponse("Function executed successfully.")

额外检查项

  • 确认Azure Function的应用设置中,Python版本与本地开发环境一致
  • 查看Azure Portal中的函数日志流(Log Stream),获取更详细的错误栈信息,排查updateRT模块是否存在依赖缺失或运行时错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:55:54