无法使用API网关运行AWS Lambda函数

2024-10-01 09:34:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个简单的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

此函数从s3存储桶中读取json文件。json文件如下所示:

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

当我在AWS控制台的function editor屏幕中进行测试时,函数成功运行,输出如下: enter image description here

Response: { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": { "id": 1, "name": "John", "pwd": "password" } }

Request 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

但是当我从API网关测试函数时,我得到了一个错误
enter image description here

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


Tags: 函数nameidjsondatas3applicationtype
1条回答
网友
1楼 · 发布于 2024-10-01 09:34:39

改变

'body': json.loads(json_data)

^{pr2}$

API网关需要一个字符串作为输出,json.dumps正是这样做的。^另一方面,{}从字符串中创建一个JSON。如果你知道NodeJS,它们相当于JSON.stringify以及JSON.parse分别是。在

示例

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

生产

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

同时

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

生产

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

此信息可在official docs中找到

编辑

还有一件事我和OP都没有注意到,data['Body'].read()不返回JSON本身,而是返回一个缓冲区。它需要先解码。在

json_data = data['Body'].read().decode('utf-8')将返回stringized JSON(当然,只是因为您的文件是JSON),所以在return语句中,您应该可以这样做:

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

相关问题 更多 >