Below Lambda function can used to add records to a dynamodb table. It also provides the steps to read a csv file from S3 bucket:
import boto3
import csv
import json
s3 = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
print("Bucket="+bucket)
print("Key="+key)
if '.csv' not in key:
return 'Not a csv file'
s3.download_file(bucket, key, '/tmp/' + key)
x=1
with open('/tmp/' + key, 'r') as infile:
for row in infile:
if x==1:
x=2
else:
ddb_key = row.strip().split(',')[0]
ddb_inc1 = row.strip().split(',')[1]
ddb_inc2 = row.strip().split(',')[2]
ddb_inc3 = row.strip().split(',')[3]
ddb_inc4 = row.strip().split(',')[4]
table = dynamodb.Table('prices_table')
response = table.put_item(
Item={
'productId': ddb_key,
'product_name': ddb_inc1,
'price': ddb_inc2,
'sale_price': ddb_inc3,
'Code': ddb_inc4
}
)
print(response)
Comments
Post a Comment