我有以下 lambda 函数代码,用于简单地打印出 S3 存储桶上传事件的作者和元数据:
from __future__ import print_function
import json
import urllib
import boto3
print('Loading function')
s3 = boto3.client('s3')
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
# bucket = event['Records'][0]['s3']['bucket']['name']
for record in event['Records']:
bucket = record[0]['s3']['bucket']['name']
key = record[0]['s3']['object']['key']
response = s3.head_object(Bucket=bucket, Key=key)
logger.info('Response: {}'.format(response))
print("Author : " + response['Metadata']['author'])
print("Description : " + response['Metadata']['description'])
但是,我在测试时遇到以下错误:
{
"stackTrace": [
[
"/var/task/lambda_function.py",
17,
"lambda_handler",
"for record in event['Records']:"
]
],
"errorType": "KeyError",
"errorMessage": "'Records'"
}
访问 S3 对象的存储桶名称和密钥名称时我做错了什么吗?如果不是,那我在这里做错了什么?
原文由 Dawny33 发布,翻译遵循 CC BY-SA 4.0 许可协议
晚会有点晚了。但这是我的第一篇文章!
解释:
当您在 lambda 面板中进行测试时 -> def lambda_handler(event, context) <- 直接注入事件。
然而,在 AWS API 中,它需要 添加映射模板 或其他 -> 事件 <- 为空,从而导致测试:
这是空指针。记录不存在,因为 -> 事件 <- 不存在。
解决方案:
您需要在 AWS API 中配置 集成请求。单击 身体映射模板。然后 添加映射模板 将内容类型设置为 application/json 然后编辑生成的映射模板:
并 编辑 Lambda 函数:
代替:
和:
不知道堆栈是否会用这个答案通知你 - 所以我叫你@Dawny33 @KevinOelen @franklinsijo
至于解释我自己想通了。但是“映射模板”来自 https://medium.com/simple-thoughts-amplified/passing-variables-from-aws-api-gateway-to-lambda-3c5d8602081b