Home

AWS Lambda Function

By Sotee Loey on Dec 23, 2023
Image post 3

What is AWS Lambda?

AWS Lambda is one of the computing services provided by AWS. It runs your code in response to events and automatically manages the compute resources it needs.

Using AWS Lambda with S3 and DynamoDB

In this case, when someone uploads a file to S3 bucket. It triggers Lambda function to read and update count item on event table in DynamoDB. These are the steps I use to do the tasks:

  1. Login into AWS console.
  2. Go to AWS Lambda.
  3. Select Create function
    • Give function a name.
    • Choose Python 3.11.
    • Click Create function.
  4. Select Add trigger
    • Add S3.
      • Event types - choose All Objects create events.
  5. Test the function.
  6. Uploaded file to S3 bucket.
  7. After receiving the object, the S3 bucket triggers the Lambda function.
  8. Review and verify that event table in DynamoDB is updated properly.

Lambda Funtion in Python, uploadcount.py

import json
import boto3

dynamodb_client = boto3.resource('dynamodb')
table = dynamodb_client.Table('event-table')

def lambda_handler(event: any, context: any):

    upload: str = event["event"]
    upload_count: int = 0

    # Get the upload count from the DynamoDB table
    result = table.get_item(Key={"event": upload})

    if "Item" in result:
        upload_count = result["Item"]["count"]

    # Increment the upload count and put the item into DynamoDB table.
    upload_count += 1
    table.put_item(Item={"event": upload, "count": upload_count})

    message: str = f"Hello {user}! You have visited us {upload_count} times."
    return {"message": message}
Subscribe to my Newsletters

Stay up-to-date with new posts