jicoing
Posted on February 7, 2021
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.
AWS Lambda
To create the function, I went in to the lambda console and clicked create.
Then I named the function and specified the lambda handler runtime:
Python 3.8
for my use case.
Once that was done, I assigned a role I had setup previously, for access to dynamodb and created the function.
API Gateway trigger
Then I added the api gateway trigger for triggering the lambda function on every API call (aws-sam-komlalebu).
Policy
The resource based policy looks like this.
app.py
Here the python code used in the lambda function.
The handler imports the modules
json
andboto3
.
- 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
- create a DynamoDB object using the AWS SDK.
dynamodb = boto3.resource('dynamodb',region_name='ap-south-1')
- use the DynamoDB object to select our table.
table = dynamodb.Table('komlalebuTable')
- store the current time in a human readable format in a variable.
now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
- define the handler function that the Lambda service will use as an entry point.
def lambda_handler(event,
context):
- 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']
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'
- return a properly formatted JSON object. This code is used for testing later (read more).
return {
'statusCode': 200,
}
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
.
CodeUri - Has the handler code location in repository.
CodeUri: komla_function/Handler - Defines the handler name.
Handler: app.lambda_handler
- Runtime - Defines the language used during runtime.
Runtime: python3.8
- Policies - Defines the access policy for the function.
Policies:
# Give DynamoDB Full Access to your Lambda Function
- AmazonDynamoDBFullAccess
- Function created in Lambda on SAM
deploy
.
- Configuring test event from lambda console.
- Testing the code -
Passed
.
- Dynamodb also got updated on table komlalebuTable.
And the lambda function was setup and deployed.
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 DynamoDBFilterExpressions
. On clickinglike
the user stores data in dynamodb table with the stringYES
appended to the visit count. However this was done as a standalone and therefore not in SAM template.
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
- 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 DynamoDBFilterExpressions
. On clickingdislike
the user stores data in dynamodb table with the stringNO
appended to the visit count. However this was done as a standalone and therefore not in SAM template.
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
Posted on February 7, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 25, 2024