[英]AWS Lambda python function to parse json from S3 and store in DynamoDB
I'm trying to write a lambda function that is triggered whenever a json file is uploaded to an s3 bucket.我正在尝试编写一个 lambda function ,只要将 json 文件上传到 s3 存储桶就会触发。 The function is supposed to parse the file and store it immediately in DynamoDB.
function 应该解析文件并将其立即存储在 DynamoDB 中。 I created a table called 'data' with the primary key set as 'date'.
我创建了一个名为“数据”的表,主键设置为“日期”。 Here's what I have for the function so far:
到目前为止,这是我对 function 的了解:
import boto3
import json
s3_client = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
json_file_name = event['Records'][0]['s3']['object']['key']
json_object = s3.Bucket(bucket).Object(json_file_name)
jsonFileReader = json_object['Body'].read()
jsonDict = json.loads(jsonFileReader)
table = dynamodb.Table('data')
table.put_item(Item = jsonDict)
Here is an example of a json file I'm trying to use:这是我尝试使用的 json 文件的示例:
{
"date": "2020-06-07 21:00:34.284421",
"ConfirmedCases": 7062067,
"ActiveCases": 3206573,
"RecoveredCases": 3450965,
"Deaths": 404529
}
Unfortunately, whenever I test the code, it throws this error:不幸的是,每当我测试代码时,它都会抛出这个错误:
[[ERROR] TypeError: string indices must be integers
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 7, in lambda_handler
bucket = event'Records'][0]['s3']['bucket']['name']]
Does anyone know how to resolve this issue?有谁知道如何解决这个问题? I've wasted so much time trying to figure this out and I still am unable to:/
我浪费了很多时间试图弄清楚这一点,但我仍然无法:/
Your error is from either of these lines.您的错误来自这些行中的任何一个。
bucket = event['Records'][0]['s3']['bucket']['name']
json_file_name = event['Records'][0]['s3']['object']['key']
However, they are correct .但是,它们是正确的。 This is the valid way of access bucket name and object key from the event generated by S3 Notifications.
这是从 S3 Notifications 生成的事件中访问存储桶名称和 object 密钥的有效方式。
It seems to me that something else is trigger your function .在我看来,还有其他东西会触发您的 function 。 Either you use
Test
option in the console and provide incorrect event
object, or there is some other event that triggers the lambda with non-S3 event.您在控制台中使用
Test
选项并提供不正确的event
object,或者有一些其他事件会触发带有非 S3 事件的 lambda。
As a quick fix, you can do the following.作为快速修复,您可以执行以下操作。 The code below will finish if
event
object does not contain Records
:如果
event
object 不包含Records
,则以下代码将完成:
def lambda_handler(event, context):
if 'Records' not in event:
print(event) # good to check what event you get
return
# and the rest of code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.