python - 将 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"
]
}
解决方案
该错误意味着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
推荐阅读
- c# - Blazor 链接 - 如果有 onclick 方法,则禁用 href
- unity3d - 是否可以在 HDRP 中设置 VR?
- android - 如何避免从 firebase 实时数据库下载相同的数据?
- java - 有没有办法检查 mongoDB 连接的正确性?
- c# - 如何将按钮从子窗体动态添加到主窗体
- sql - 如果 col b 的值匹配,则用 col a 的值填充 col a 的 NULL
- python - OpenCV:如何计算灰度的平均值并将输出保存到 txt 文件
- android - 将两个 TextView 放在一个聊天气泡中
- javascript - 延迟屏蔽输入字段的时间
- php - 获取对按键搜索的php数组元素的引用