AWS S3中的"KeyError:'Records'" - Lambda触发器

Daw*_*y33 7 python amazon-s3 amazon-web-services aws-lambda

我有以下lambda函数代码,用于简单地打印S3存储桶的上传事件的Author和元数据:

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'])
Run Code Online (Sandbox Code Playgroud)

但是,我在测试时收到以下错误:

{
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      17,
      "lambda_handler",
      "for record in event['Records']:"
    ]
  ],
  "errorType": "KeyError",
  "errorMessage": "'Records'"
}
Run Code Online (Sandbox Code Playgroud)

访问S3对象的存储桶名称和密钥名称时,我是否做错了什么?如果没有,那么我在这里做错了什么?

esr*_*esr 6

有点迟到了.但这是我的第一篇文章!

说明:

当你在lambda面板中测试时 - > def lambda_handler(event,context)< - 直接注入事件.

但是在AWS API中,必须添加映射模板或其他 - > event < - 为空,从而导致测验:

"errorType":"KeyError","errorMessage":"'Records'"

这是空指针.记录不存在,因为 - >事件< - 不存在.

解:

您需要在AWS API中配置Integration Request.单击Body Mapping Templates.然后将映射模板 集内容类型添加application/json 然后编辑生成的映射模板:

{
  "body" : $input.json('$'),
  "headers": {
    #foreach($header in $input.params().header.keySet())
    "$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end

    #end
  },
  "method": "$context.httpMethod",
  "params": {
    #foreach($param in $input.params().path.keySet())
    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "query": {
    #foreach($queryParam in $input.params().querystring.keySet())
    "$queryParam": "$util.escapeJavaScript($input.params().querystring.get($queryParam))" #if($foreach.hasNext),#end

    #end
  }  
}
Run Code Online (Sandbox Code Playgroud)

编辑Lambda函数:

更换:

在事件['记录']中记录:

有:

在事件['查询'] ['记录']中记录

不知道堆栈会不会给你这个答案 - 所以我叫你@ Dawny33 @KevinOelen @franklinsijo

至于解释,我自己想到了.然而,"映射模板"来自https://medium.com/simple-thoughts-amplified/passing-variables-from-aws-api-gateway-to-lambda-3c5d8602081b

  • 如果我尝试在没有 API 调用的情况下执行 lambda 那么我该如何解决这个问题呢? (4认同)