DEV Community

Cover image for 10. Python
jicoing
jicoing

Posted on • Edited on

10. Python

The website uses a lambda function to push data into the backend Dynamodb table with handler written in python 3.8 .
AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes.

Alt Text

AWS Lambda

Alt Text

To create the function, I went in to the lambda console and clicked create.
Alt Text

Then I named the function and specified the lambda handler runtime: Python 3.8 for my use case.

Alt Text

Once that was done, I assigned a role I had setup previously, for access to dynamodb and created the function.

Alt Text

API Gateway trigger

Then I added the api gateway trigger for triggering the lambda function on every API call (aws-sam-komlalebu).

Alt Text

Policy

The resource based policy looks like this.
Alt Text

app.py

Here the python code used in the lambda function.

Alt Text

The handler imports the modules json and boto3.

  • import the json utility package since we will be working with a JSON object.
  • import the AWS SDK (for Python the package name is boto3).
  • import two packages to help us with dates and date formatting.
                            import json
                            import boto3
                            from time import gmtime, strftime
Enter fullscreen mode Exit fullscreen mode
  • create a DynamoDB object using the AWS SDK.
                            dynamodb = boto3.resource('dynamodb',region_name='ap-south-1')
Enter fullscreen mode Exit fullscreen mode
  • use the DynamoDB object to select our table.
                 table = dynamodb.Table('komlalebuTable')
Enter fullscreen mode Exit fullscreen mode
  • store the current time in a human readable format in a variable.
               now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
Enter fullscreen mode Exit fullscreen mode
  • define the handler function that the Lambda service will use as an entry point.
                            def lambda_handler(event, 
                            context):
Enter fullscreen mode Exit fullscreen mode
  • extract values from the event object we got from the Lambda service and store in a variable.
                         try:
                         event = json.loads(event['body'])
                         visitor = event['visitorCount'] +' '+ 
                         event['visitorResponse']
Enter fullscreen mode Exit fullscreen mode

visitorCount and visitorResponse are fetched from the callAPI Javascript function (read more) and concatenated into visitor variable.

  • write visitor and time to the DynamoDB table using the object we instantiated and save response in a variable using response method.
                        response = table.put_item(
                        Item={
                            'id': visitor,
                            'LatestGreetingTime':now
                             })
                       except:
                       visitor = 'request error'
Enter fullscreen mode Exit fullscreen mode
  • return a properly formatted JSON object. This code is used for testing later (read more).
                      return {
                      'statusCode': 200,
                      }
Enter fullscreen mode Exit fullscreen mode

AWS::Serverless::Function

This was the manual way of doing things, the final application has the lambda function defined in SAM template as below in template.yml (read more). With the function name as KomlalebuFunction.

Alt Text

  • CodeUri - Has the handler code location in repository.
    CodeUri: komla_function/

  • Handler - Defines the handler name.

  Handler: app.lambda_handler
Enter fullscreen mode Exit fullscreen mode
  • Runtime - Defines the language used during runtime.
  Runtime: python3.8
Enter fullscreen mode Exit fullscreen mode
  • Policies - Defines the access policy for the function.
  Policies:
  # Give DynamoDB Full Access to your Lambda Function
  - AmazonDynamoDBFullAccess
Enter fullscreen mode Exit fullscreen mode
  • Function created in Lambda on SAM deploy.

Alt Text

  • Configuring test event from lambda console.

Alt Text

  • Testing the code - Passed.

Alt Text

Alt Text

And the lambda function was setup and deployed.

Alt Text

Miscellaneous

Update

I also setup a visitor stats HTML table, combining stats for visitor counter, likes, dislikes.

  • likes - I had to setup a separate API and Lambda function (komlalikesFunction) that runs a table scan on the backend table komlalebuTable that fetches the records based on DynamoDB FilterExpressions. On clicking like the user stores data in dynamodb table with the string YES appended to the visit count. However this was done as a standalone and therefore not in SAM template.

Alt Text

There is a separate lambda funtion that scans the table with the primary key id containing the string yes and gives back the result count. This function is called by a separate API everytime the page gets loaded.

komlalikesFunction

Alt Text

  • Dislikes - I had to setup a separate API and Lambda function (komladislikesFunction) that runs a table scan on the backend table komlalebuTable that fetches the records based on DynamoDB FilterExpressions. On clicking dislike the user stores data in dynamodb table with the string NO appended to the visit count. However this was done as a standalone and therefore not in SAM template.

Alt Text

There is a separate lambda funtion that scans the table with the primary key id containing the string NO and gives back the result count. This function is called by a separate API everytime the page gets loaded.

komladislikesFunction

Alt Text

Alt Text

Top comments (0)