【问题标题】:How to send and return a JSON response through a lambda function aws如何通过 lambda 函数 aws 发送和返回 JSON 响应
【发布时间】:2021-10-23 04:35:15
【问题描述】:

我有一个 Amazon webservices 的闭包,称为 lambda 函数,其委托定义如下:

def lambda_handler(event, context):
    logger.info('Ev° %s', event)

    if event['action'] == "getPosition":
        getPosition(event, context)

def getPosition(event, context):

    # read position from file
    positionLoaded = readPosition(pId=int(json.loads(str(event['body']['id']))))

    # build response
    response = {
        "statusCode": 200,
        "body": json.dumps(positionLoaded, indent=4),
        "message": "OK",
        "headers": {
            "Content-Type": "application/json",
        }
    }

return response


# Reads position in json file from s3 Bucket with pId
def readPosition(pId: int):
    positionFromBucketJSON = s3_client.get_object(Bucket="bucketName", Key=str(pId) + ".json")
    return json.loads(positionFromBucketJSON['Body'].read().decode('utf-8'))

当我向 lambda 函数发送请求时如下:

{
  "action": "getPosition",
  "body": {
    "id": 2021152530123456
  }
}

我收到一个错误来自 lambda 函数的响应,如下所示:

{"errorMessage": "'Not Found'", "errorType": "KeyError", "stackTrace": ["  File \"/var/task/positionService.py\", line 58, in lambda_handler\n    getPosition(event, context, callback=None)\n", "  File \"/var/task/positionService.py\", line 76, in getPosition\n    message = "not existing at all!"}

我不知道为什么,因为 JSON-File 2021152530123456.json 确实直接存在于 s3 存储桶中。

您能帮忙找出在这种情况下可能出现的错误吗?

【问题讨论】:

    标签: amazon-web-services amazon-s3 aws-lambda


    【解决方案1】:

    Python Lambda function handler 采用 2 个参数(事件、上下文),而不是 3 个参数(事件、上下文、回调)。您可能一直在阅读 JavaScript 文档,其中 Lambda 函数处理程序具有第三个参数(回调)。

    这是一个返回 JSON 有效负载的 Python Lambda 函数示例:

    import json
            
    def lambda_handler(event, context):
        return {
            "statusCode": 200,
            "headers": {
                "Content-Type": "application/json"
            },
            "body": json.dumps({
                "id": 12,
                "description": "hoverboard"
            })
        }
    

    在您的原始代码中,您还有两个额外的问题:

    1. 您的 Lambda 处理程序不返回任何内容(它应该返回 getPosition(event, context)
    2. 您的 getPosition() 函数的 return 语句缩进错误(更正缩进)

    【讨论】:

    • 我,我要去看看,然后回来,感谢您提供的详细信息,我也从许多其他人那里阅读了该文档。到时候见
    • 我,我现在得到 null 作为更新后的回报!
    • 您当前的代码是什么样的?很难诊断出我们看不到的东西。
    • 我刚刚用更新的代码更新了问题:)
    • 您的 Lambda 处理程序,如所写,不返回任何内容。并且您的 getPosition() 函数的 return 语句缩进错误。
    【解决方案2】:

    我通过在委托给 getPosition(...) 函数的同时向主 lambda 函数添​​加 return 来解决我的问题,它看起来如下所示:

    def lambda_handler(event, context):
        logger.info('Ev° %s', event)
    
        if event['action'] == "getPosition":
            return getPosition(event, context)
    

    【讨论】:

      猜你喜欢
      • 2016-08-15
      • 2019-09-28
      • 2020-04-24
      • 2017-12-29
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2018-01-15
      相关资源
      最近更新 更多