首页 > 解决方案 > 将 csv 更新为 dynamodb 时出现 KeyError

问题描述

昨天我的代码在将我的 csv 插入 dynamo db 时正在工作,它无法识别bucket_name昨天在云监视日志中的事件在上传时可见,但今天它不是

import boto3

s3_client = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    #bucket_name = event['query']['Records'][0]['s3']['bucket']['name']
    print (bucket_name)
    s3_file_name = event['Records'][0]['s3']['object']['key']
    resp = s3_client.get_object(Bucket=bucket_name,Key=s3_file_name)
    data = resp['Body'].read().decode('utf-8')
    employees = data.split("\n")
    table = dynamodb.Table('employees')
    for emp in employees:
        emp_data = emp.split(',')
        print (emp_data)

        try:
            table.put_item(
                Item = {
                    "emp_id": emp_data[0],
                    "Name": emp_data[1],
                    "Company": emp_data[2]
                }
            )
        except Exception as e:
            print ('endof file')
    return 'files saved to Dynamodb'

今天我收到以下错误

回复:

{
  "errorMessage": "'Records'",
  "errorType": "KeyError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 7, in lambda_handler\n    bucket_name = event['Records'][0]['s3']['bucket']['name']\n"
  ]
}

标签: pythonamazon-web-servicesamazon-s3aws-lambdaamazon-dynamodb

解决方案


该错误意味着event不包含Records.

要检查这一点并防止出现错误,您可以执行以下操作:

def lambda_handler(event, context):

    if 'Records' not in event:
        # execute some operations that you want
        # in case there are no Records 
        # in the event

        return


    # continue processing Records if 
    # they are available
    event['Records'][0]['s3']['bucket']['name']

    # the rest of your code

推荐阅读