AWS API网关Lambda失败,状态为200

问题描述 投票:0回答:1

我正在编写MicroService,我的lambda处理程序在请求的主体中采用JSON并构建了Jinja2模板。我的Lambda函数正常工作,并返回状态码200,但是当我通过API网关调用该函数时,得到了502响应。

def lambda_handler(event, context):
    try:
        file_object = s3.get_object(Bucket= 'bucket_name', Key='object_name')
        file_content = file_object["Body"].read().decode('utf-8')
        template = Template(file_content)
        rendered_template = template.render(resume = request_body)
        # Do some logic to place render in s3 and get path
        response = {
            'statusCode': 200,
            'header': {'Content-Type': 'application/json'},
            'body': 'path to file'
        }
        return response
    except Exception as e:
        print(e)
        raise e

我正在使用的请求正文类似于:

{
  "username": "john-doe",
  "location": "US",
  .
  .
  .
}

我收到的响应错误是:

{
  "errorMessage": "'str object' has no attribute 'lastName'",
  "errorType": "UndefinedError",
  "stackTrace": [
    "  File \"/var/task/resume_service.py\", line 39, in lambda_handler\n    raise e\n",
    "  File \"/var/task/resume_service.py\", line 25, in lambda_handler\n    generate = template.render(resume=request_body)\n",
    "  File \"/var/task/jinja2/asyncsupport.py\", line 76, in render\n    return original_render(self, *args, **kwargs)\n",
    "  File \"/var/task/jinja2/environment.py\", line 1008, in render\n    return self.environment.handle_exception(exc_info, True)\n",
    "  File \"/var/task/jinja2/environment.py\", line 780, in handle_exception\n    reraise(exc_type, exc_value, tb)\n",
    "  File \"/var/task/jinja2/_compat.py\", line 37, in reraise\n    raise value.with_traceback(tb)\n",
    "  File \"<template>\", line 28, in top-level template code\n",
    "  File \"/var/task/jinja2/environment.py\", line 411, in getitem\n    return obj[argument]\n"
  ]
}

我自己调用Lambda函数如何成功,但是通过API网关调用它却失败?

python-3.x amazon-web-services aws-lambda aws-api-gateway
1个回答
0
投票

[将API Gateway与Lambda代理集成一起使用时,API Gateway希望从Lambda返回的数据采用特定的格式,如here所示。您还需要在返回的响应中添加isBase64Encoded标志。

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... },
    "body": "..."
}

跳过代码,看起来这仅在函数成功返回时才适用,但是如果发生任何错误,它将引发异常-API Gateway不会期望;因此是502格式错误的代理。

要对此进行更多说明,请检查控制台和API网关的两个请求之间的区别。由于我们必须设置特定的JSON有效负载才能从控制台(或任何调用服务)调用该函数,因此我将在处理程序之后打印出该事件,以检查API Gateway请求的事件结构是什么,并在从控制台以查看是否仍然有效。我正在猜测这样做,因为错误声明'str object' has no attribute 'lastName',所以无法正常工作。

如果这与控制台上的API Gateway有效负载兼容,我将检查API Gateway和Lambda函数日志(带有事件打印)的完整请求/响应日志,以使两个请求之间更加清晰。

© www.soinside.com 2019 - 2024. All rights reserved.