简体   繁体   English

无法使用 API Gateway 运行 AWS Lambda 函数

[英]Unable to run AWS Lambda function with API Gateway

I have created a simple python 3.7 lambda function:我创建了一个简单的 python 3.7 lambda 函数:

import json
import boto3

s3 = boto3.client("s3")


def lambda_handler(event, context):
    bucket = "nubi-data"
    key = "core/user.json"

    try:
        data = s3.get_object(Bucket=bucket, Key=key)
        json_data = data['Body'].read()

        #return json_data

        return {
            'statusCode': 200,
            "headers": {"Content-Type": "application/json"},
            'body': json.loads(json_data)
            }


    except Exception as e:
        print(e)
        raise e

This function reads a json file from an s3 bucket.此函数从 s3 存储桶中读取 json 文件。 The json file looks like: json 文件如下所示:

{ "id": 1, "name": "John", "pwd": "password" } { "id": 1, "name": "John", "pwd": "密码" }

The function runs successfully when I test from within function editor screen in AWS console with the following output:当我从 AWS 控制台的函数编辑器屏幕中测试时,该函数成功运行,输出如下: 在此处输入图片说明

Response: { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": { "id": 1, "name": "John", "pwd": "password" } }响应:{“statusCode”:200,“headers”:{“Content-Type”:“application/json”},“body”:{“id”:1,“name”:“John”,“pwd”: “密码” } }

Request ID: "f57de02f-44dd-4854-9df9-9f3a8c90031d"请求 ID:“f57de02f-44dd-4854-9df9-9f3a8c90031d”

Function Logs: START RequestId: f57de02f-44dd-4854-9df9-9f3a8c90031d Version: $LATEST END RequestId: f57de02f-44dd-4854-9df9-9f3a8c90031d REPORT RequestId: f57de02f-44dd-4854-9df9-9f3a8c90031d Duration: 260.70 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 84 MB函数日志: START RequestId:f57de02f-44dd-4854-9df9-9f3a8c90031d 版本:$LATEST END RequestId:f57de02f-44dd-4854-9df9-9f3a8c90031d REPORT RequestId:f544de09d-dvation-ds90031d-Dillation-Dillation-Dillation-Dillation-Dillation-Billion030300000000 300 ms 内存大小:128 MB 已用最大内存:84 MB

But when I test the function from the API Gateway, I get the error但是当我从 API Gateway 测试该功能时,出现错误
在此处输入图片说明

Thu Mar 21 21:04:08 UTC 2019 : Endpoint response body before transformations: {"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": {"id": 1, "name": "John", "pwd": "password"}} Thu Mar 21 21:04:08 UTC 2019 : Execution failed due to configuration error: Malformed Lambda proxy response Thu Mar 21 21:04:08 UTC 2019 : Method completed with status: 502 2019 年 3 月 21 日星期四 21:04:08 UTC:转换前的端点响应正文:{"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": {"id" : 1, "name": "John", "pwd": "password"}} Thu Mar 21 21:04:08 UTC 2019:由于配置错误而导致执行失败:Lambda 代理响应格式错误,Thu Mar 21 21:04:08 UTC 2019:方法完成,状态:502

Change改变

'body': json.loads(json_data)

to

'body': json.dumps(json_data)

API Gateway expects a String as output and json.dumps does exactly this. API Gateway 需要一个 String 作为输出,而json.dumps正是这样做的。 json.loads , on the other hand, creates a JSON out of a String.另一方面, json.loads从字符串中创建一个 JSON。 If you know NodeJS, they're equivalent to JSON.stringify and JSON.parse, respectively.如果您了解 NodeJS,它们分别相当于 JSON.stringify 和 JSON.parse。

Example例子

json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])

produces产生

'["foo", {"bar": ["baz", null, 1.0, 2]}]' '["foo", {"bar": ["baz", null, 1.0, 2]}]'

while尽管

json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')

produces产生

[u'foo', {u'bar': [u'baz', None, 1.0, 2]}] [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

This information is available in the official docs此信息可在官方文档中找到

EDIT编辑

One more thing both the OP and I missed is that data['Body'].read() doesn't return the JSON itself but a buffer instead. OP 和我都错过的另一件事是data['Body'].read()不返回 JSON 本身,而是返回一个缓冲区。 It needs to be decoded first.需要先解码。

json_data = data['Body'].read().decode('utf-8') will return the stringified JSON already (just because your file is a JSON, of course), so on your return statement you should be able to simply do it like this: json_data = data['Body'].read().decode('utf-8')将已经返回字符串化的 JSON(当然只是因为你的文件是 JSON),所以在你的 return 语句中你应该能够只需这样做:

return {
         'statusCode': 200,
         "headers": {"Content-Type": "application/json"},
         'body': json_data
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM