如何通过 lambda 函数 aws 发送和返回 JSON 响应

问题描述:

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

I have an a closure by Amazon webservices called lambda function with delegation defined as following:

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 函数发送 请求 如下:

When I send a request to the lambda function as following:

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

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

I get an error response from the lambda function as following:

{"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 存储桶中.

I don't know why since JSON-File 2021152530123456.json do exist directly in s3 bucket.

你能帮忙弄清楚在这种情况下可能是什么错误吗?

Could you help to figure out what the error could be in this case?

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

The Python Lambda function handler takes 2 parameters (event, context), not 3 parameters (event, context, callback). You may have been reading JavaScript documentation, where a Lambda function handler has a 3rd parameter (callback).

以下是返回 JSON 负载的 Python Lambda 函数示例:

Here is an example of a Python Lambda function that returns a JSON payload:

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

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

In your original code, you have two additional problems:

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