【问题标题】:Function returning null as response [duplicate]函数返回 null 作为响应 [重复]
【发布时间】:2021-08-29 03:31:22
【问题描述】:

我有一个 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 函数的响应,如下所示:

    {
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
null

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

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

【问题讨论】:

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


    【解决方案1】:

    Lambda 处理程序返回语句

    您的 lambda_handler 缺少 return 语句,因此返回 None。根据AWS Documentation

    如果处理程序返回 None,就像没有 return 语句的 Python 函数隐式执行的那样,运行时返回 null。

    相信你需要返回getPosition(event, context)如下

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2012-05-04
      • 2021-09-09
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      相关资源
      最近更新 更多