无法通过API Gateway运行AWS Lambda函数 [英] Unable to run AWS Lambda function with API Gateway
问题描述
我创建了一个简单的python 3.7 lambda函数:
I have created a simple python 3.7 lambda function:
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文件如下:
This function reads a json file from an s3 bucket. The json file looks like:
{"id":1,"name":"John","pwd":密码"}
{ "id": 1, "name": "John", "pwd": "password" }
当我在AWS控制台的功能编辑器屏幕中进行测试时,该功能成功运行,并显示以下输出:
The function runs successfully when I test from within function editor screen in AWS console with the following output:
响应:{"statusCode":200,"headers":{ "Content-Type":"application/json"},"body":{ "id":1 "name":"John", "pwd":密码"}}
Response: { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": { "id": 1, "name": "John", "pwd": "password" } }
请求ID:"f57de02f-44dd-4854-9df9-9f3a8c90031d"
Request ID: "f57de02f-44dd-4854-9df9-9f3a8c90031d"
功能日志:START RequestId:f57de02f-44dd-4854-9df9-9f3a8c90031d 版本:$ LATEST END RequestId:f57de02f-44dd-4854-9df9-9f3a8c90031d 报告RequestId:f57de02f-44dd-4854-9df9-9f3a8c90031d持续时间: 260.70 ms计费时间:300 ms内存大小:128 MB使用的最大内存:84 MB
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网关测试功能时,出现错误消息
But when I test the function from the API Gateway, I get the error
UTC 2019年3月21日21:04:08:端点响应正文之前 转换:{"statusCode":200,"headers":{"Content-Type": "application/json"},"body":{"id":1,1,"name":"John","pwd": "password"}}周三3月21日21:04:08 UTC:由于执行失败 配置错误:Lambda代理响应格式错误,3月21日,星期四 21:04:08 UTC 2019:方法完成,状态:502
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
推荐答案
更改
'body': json.loads(json_data)
到
'body': json.dumps(json_data)
API网关希望将字符串作为输出,而json.dumps
正是这样做的.另一方面,json.loads
从字符串中创建一个JSON.如果您知道NodeJS,它们分别相当于JSON.stringify和JSON.parse.
API Gateway expects a String as output and json.dumps
does exactly this. json.loads
, on the other hand, creates a JSON out of a String. If you know NodeJS, they're equivalent to JSON.stringify and JSON.parse, respectively.
示例
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
产生
'["foo",{"bar":["baz",null,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]}]
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
此信息可在官方文档
编辑
OP和我都错过的另一件事是data['Body'].read()
不会返回JSON本身,而是返回一个缓冲区.需要先将其解码.
One more thing both the OP and I missed is that data['Body'].read()
doesn't return the JSON itself but a buffer instead. It needs to be decoded first.
json_data = data['Body'].read().decode('utf-8')
将已经返回字符串化的JSON(当然,只是因为您的文件是JSON),因此在return语句上,您应该能够像这样简单地做到这一点:
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:
return {
'statusCode': 200,
"headers": {"Content-Type": "application/json"},
'body': json_data
}
这篇关于无法通过API Gateway运行AWS Lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!