【问题标题】:KeyError while updating csv to dynamodb将 csv 更新为 dynamodb 时出现 KeyError
【发布时间】:2020-06-30 10:49:25
【问题描述】:

昨天我的代码在将我的 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"
  ]
}

【问题讨论】:

    标签: python amazon-web-services amazon-s3 aws-lambda amazon-dynamodb


    【解决方案1】:

    错误表示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
    

    【讨论】:

    • 为什么昨天我能够插入到 dynamodb 中工作
    • @aysh 我没有答案。似乎您的 lambda 被调用的事件类型与常规 S3 通知事件不同。
    • 你能在下面回答吗,连赏金都帮不上忙。 stackoverflow.com/questions/62587459/…
    • @aysh 感谢您的链接。我将研究新问题。我知道我目前的回答足以解决 Records 的当前问题?
    • 我将处理您的答案并进行编辑,以便新人受益。谢谢马尔辛。你真棒
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2020-01-31
    • 2022-01-24
    • 2017-04-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多