awsstudent
HMtfKSksL&%jK72
498648721753
us-west-2
us-west-2:13b8d29b-26ce-459e-b872-b4cf2b25690a
# Load-Inventory Lambda function
#
# This function is triggered by an object being created in an Amazon S3 bucket.
# The file is downloaded and each line is inserted into a DynamoDB table.
import json, urllib, boto3, csv
# Connect to S3 and DynamoDB
s3 = boto3.resource('s3')
dynamodb = boto3.resource('dynamodb')
# Connect to the DynamoDB tables
inventoryTable = dynamodb.Table('Inventory');
# This handler is executed every time the Lambda function is triggered
def lambda_handler(event, context):
# Show the incoming event in the debug log
print("Event received by Lambda function: " + json.dumps(event, indent=2))
# Get the bucket and object key from the event
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])
localFilename = '/tmp/inventory.txt'
# Download the file from S3 to the local filesystem
try:
s3.meta.client.download_file(bucket, key, localFilename)
except Exception as e:
print(e)
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
raise e
# Read the Inventory CSV file
with open(localFilename) as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
# Read each row in the file
rowCount = 0
for row in reader:
rowCount += 1
# Show the row in the debug log
print(row['store'], row['item'], row['count'])
try:
# Insert Store, Item, and Count into the Inventory table
inventoryTable.put_item(
Item={
'Store': row['store'],
'Item': row['item'],
'Count': int(row['count'])})
except Exception as e:
print(e)
print("Unable to insert data into DynamoDB table".format(e))
# Finished!
return "%d counts inserted" % rowCount
store,item,count
Berlin,Echo Dot,12
Berlin,Echo (2nd Gen),19
Berlin,Echo Show,18
Berlin,Echo Plus,0
Berlin,Echo Look,10
Berlin,Amazon Tap,15
https://kgit.qwiklabs.com/classrooms/471/labs/3027#sms-steps
# Stock Check Lambda function
#
# This function is triggered when values are inserted into the Inventory DynamoDB table.
# Inventory counts are checked, and if an item is out of stock, a notification is sent to an SNS topic.
import json, boto3
# This handler is executed every time the Lambda function is triggered
def lambda_handler(event, context):
# Show the incoming event in the debug log
print("Event received by Lambda function: " + json.dumps(event, indent=2))
# For each inventory item added, check if the count is zero
for record in event['Records']:
newImage = record['dynamodb'].get('NewImage', None)
if newImage:
count = int(record['dynamodb']['NewImage']['Count']['N'])
if count == 0:
store = record['dynamodb']['NewImage']['Store']['S']
item = record['dynamodb']['NewImage']['Item']['S']
# Construct message to be sent
message = store + ' is out of stock of ' + item
print(message)
# Connect to SNS
sns = boto3.client('sns')
alertTopic = 'NoStock'
snsTopicArn = [t['TopicArn'] for t in sns.list_topics()['Topics']
if t['TopicArn'].lower().endswith(':' + alertTopic.lower())][0]
# Send message to SNS
sns.publish(
TopicArn=snsTopicArn,
Message=message,
Subject='Inventory Alert!',
MessageStructure='raw'
)
# Finished!
return 'Successfully processed {} records.'.format(len(event['Records']))
728x90
'Cloud > AWS' 카테고리의 다른 글
AWS -ECS (ECR에 이미지 푸시) (0) | 2022.07.10 |
---|---|
AWS - Auto Scaling, Load Balancer (0) | 2022.06.23 |
AWS - Wordpress와 RDS를 이용한 DB Server 연결하기 (0) | 2022.06.23 |
AWS - Auto Scaling (0) | 2022.06.23 |
AWS - RDS (Relational Database Service) (0) | 2022.06.22 |