Learn and Be Curious











from __future__ import print_function

import json
import urllib
import boto3
import csv

print('Loading function')

customerTableName = 'Customer'
transactionsTableName = 'Transactions'

s3 = boto3.resource('s3')
dynamodb = boto3.resource('dynamodb')
customerTable = dynamodb.Table(customerTableName);
transactionsTable = dynamodb.Table(transactionsTableName);

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))

    # Get the bucket and object key from the event
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
    trnFileName = '/tmp/transactions.txt'
    try:
        s3.meta.client.download_file(bucket, key, trnFileName)
    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 Transactions CSV file. Delimiter is the '|' character
    with open(trnFileName) as csvfile:
        reader = csv.DictReader(csvfile, delimiter='|')
        for row in reader:
            print(row['customer_id'], row['customer_address'], row['trn_id'], row['trn_date'], row['trn_amount'])
            # Insert customer id and address in customer DynamoDB table
            try:
                resp = customerTable.put_item(
                    Item={
                        'CustomerId': row['customer_id'],
                        'Address': row['customer_address']})
                resp = transactionsTable.put_item(
                    Item={
                        'CustomerId': row['customer_id'],
                        'TransactionId': row['trn_id'],
                        'TransactionDate': row['trn_date'],
                        'TransactionAmount': int(row['trn_amount'])})
            except Exception as e:
                 print(e)
                 print("Unable to insert data into DynamoDB table".format(e))

    return "done"









from __future__ import print_function

import json
import boto3

print('Loading function')

### STUDENT TODO: Update the value of snsTopicArn ###
snsTopicArn = ''

dynamodb = boto3.resource('dynamodb')
transactionTotalTableName = 'TransactionTotal'
transactionsTotalTable = dynamodb.Table(transactionTotalTableName);

sns = boto3.client('sns')

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    for record in event['Records']:
        customerId = record['dynamodb']['NewImage']['CustomerId']['S']
        transactionAmount = int(record['dynamodb']['NewImage']['TransactionAmount']['N'])

        response = transactionsTotalTable.update_item(
            Key={
                'CustomerId': customerId
            },
            UpdateExpression="add accountBalance :val",
            ExpressionAttributeValues={
                ':val': transactionAmount
            },
            ReturnValues="UPDATED_NEW"
        )
        print("Added transaction to account balance in TransactionTotal table")

        latestAccountBalance = response['Attributes']['accountBalance']
        print("Latest account balance: ".format(latestAccountBalance))

        if latestAccountBalance  >= 1500:
            message = '{"customerID": "' + customerId + '", ' + '"accountBalance": "' + str(latestAccountBalance) + '"}'
            print(message)
            print("Account balance is very high: ".format(latestAccountBalance))
            sns.publish(
                TopicArn=snsTopicArn,
                Message=message,
                Subject='Warning! Account balance is very high',
                MessageStructure='raw'
            )


    return 'Successfully processed {} records.'.format(len(event['Records']))







  snsTopicArn = '_<ARN for HighAccountBalanceAlertSNSTopic>_'






https://s3-us-west-2.amazonaws.com/us-west-2-aws-staging/awsu-ilt/academy-cca/v3.0/labs/lab12-serverless/scripts/transactions.txt


customer_id|customer_address|trn_id|trn_date|trn_amount
C1|1 Smith Street, London|T01|03/16/2016|100
C2|2 Smith Street, London|T02|03/16/2016|200
C2|2 Smith Street, London|T03|03/16/2016|50
C2|2 Smith Street, London|T04|03/16/2016|300
C2|2 Smith Street, London|T05|03/16/2016|100
C2|2 Smith Street, London|T06|03/16/2016|150
C2|2 Smith Street, London|T07|03/16/2016|400
C2|2 Smith Street, London|T08|03/16/2016|50
C2|2 Smith Street, London|T09|03/16/2016|50
C2|2 Smith Street, London|T10|03/16/2016|10
C2|2 Smith Street, London|T11|03/16/2016|10
C2|2 Smith Street, London|T12|03/16/2016|10
C2|2 Smith Street, London|T13|03/16/2016|20
C1|1 Smith Street, London|T14|03/16/2016|51
C1|1 Smith Street, London|T15|03/16/2016|25
C1|1 Smith Street, London|T16|03/16/2016|27
C1|1 Smith Street, London|T17|03/16/2016|29
C1|1 Smith Street, London|T18|03/16/2016|19
C1|1 Smith Street, London|T19|03/16/2016|33
C1|1 Smith Street, London|T20|03/16/2016|35
C1|1 Smith Street, London|T21|03/16/2016|39
C1|1 Smith Street, London|T22|03/16/2016|41
C1|1 Smith Street, London|T23|03/16/2016|199
C2|2 Smith Street, London|T24|03/16/2016|400





        {
          "Type" : "Notification",
          "MessageId" : "eb0d030d-5f2d-5695-8f22-4c68d0335c0b",
          "TopicArn" : "arn:aws:sns:us-east-1:123456789:HighAccountBalanceAlertSNSTopic",
          "Subject" : "Warning! Account balance is very high",
          "Message" : "{\"customerID\": \"C2\", \"accountBalance\": \"1750\"}",
        ...
        }





'Cloud > AWS' 카테고리의 다른 글

Using Auto Scaling with AWS Lambda  (0) 2017.06.02
Making Your Environment Highly Available  (0) 2017.06.02
Multi-Region Failover with Route 53  (0) 2017.06.02
Developing a web app on AWS  (0) 2017.06.02
exercise 1  (0) 2017.06.01