boto3 lambda 负载始终返回 NULL [python,同步调用]

问题描述

我正在使用 Lambda 来触发阶跃函数。它在触发阶跃函数方面工作正常,但我还需要 lambda 返回状态机执行 arn(不是状态机 arn)。我需要执行 arn,因为我将整个过程作为 github 操作工作流来实现,所以我需要它来检查状态机的状态(运行/成功/失败/中止)。

我为 github 操作获取 lambda 返回的代码,包装为 docker-compose 服务:

client = boto3.client("lambda",region_name="us-west-1")
lambda_response = client.invoke(
    FunctionName="my-lambda",InvocationType="RequestResponse",Payload=json.dumps({"detail-type": "gh-action"}),)
payload = json.loads(lambda_response["Payload"].read()) # tried .decode() too
print("payload:",payload) # payload prints None as a whole,not {"sfn_exe_arn": None}

我的 lambda 函数的相关部分:

    try:
        client = boto3.client("stepfunctions")
        response = client.start_execution(
            stateMachineArn=STATE_MACHINE_ARN,name=run_name,input=json.dumps(
                {"runName": run_name,"model_name": MODEL_NAME,"queries": QUERIES}
            ),)
        sfn_exe_arn = response["executionArn"]
    except Exception as e:
        raise e
  
    return {"sfn_exe_arn": sfn_exe_arn}
    # this `sfn_exe_arn` can print out with expected value in console
    # but it does not return when called in github action

当我从控制台调用这个 lambda 时,大多数时候它会按预期返回,即 {"sfn_exe_arn": sfn_exe_arn},但有时它也会返回 null

当我作为 github 操作工作流的一部分调用此 lambda 时,返回始终为 null(返回 lambda_response,只有 payload 部分始终为 null

谁能帮我理解为什么会有这个差距?显然我的 lambda 得到了 executionArn,但它只是没有返回到 client.invoke()

整个lambda_response(在截图中被命名为response):

enter image description here

解决方法

您必须解码从 StreamingBody.read() 获得的字节流

.decode() 添加到您从读取响应负载中获得的 bytes 对象。

payload = json.loads(lambda_response["Payload"].read().decode())
,

糟糕,我没有彻底尝试其他帖子的答案。谢谢@jarmod 在评论中指出了解决方案:您需要在读取之前将 StreamingBody 分配给变量。链接:Lambda Return Payload botocore.response.StreamingBody object prints but then empty in variable