EricFr@nkenberger.com

HOME   RESUME/CONTACT   GITHUB

[12-21-2020] | Lambda Visitor Count


The finale! I have the following things working.

  1. Write to DynamoDB with Python
  2. API triggering a Lambda function
  3. Incrementing user count in a table


Time to bring it all together. Here's my working code in Lambda:

 
        import json
        import boto3
        from boto3.dynamodb.conditions import Key

        def lambda_handler(event, context):

                dynamodb = boto3.resource('dynamodb')
                table=dynamodb.Table('visitorCounter')

                get = table.get_item(
                        Key={'countId': '1', 'countNo': '1'}
                )

                itemGot = get['Item']
                visitorNo = int(itemGot['countNos'])

                print("pre inc", visitorNo)

                visitorNo += 1

                print("incremented", visitorNo)

                table.put_item(
                Item={
                        'countId': '1',
                        'countNo': '1',
                        'countNos': str(visitorNo)
                })

                responseObject = {}
                responseObject['statusCode'] = 200
                responseObject['headers'] = {
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Headers": "Content-Type",
                        "Access-Control-Allow-Methods": "OPTIONS,GET"
                        }
                
        responseObject['headers']['Content-Type'] ='application/json'
        responseObject['body'] = json.dumps(visitorNo)
                
        return responseObject
         


Pre inc and post inc prints are in there for debugging in CloudWatch in case I need to take a quick look. I need to give the function permissions to access the database. I already set permissions for this to access Cloudwatch, so I'm just going to edit the IAM policy to include my db. Only GetItem and PutItem are used, so those are the only ones that get permission.

IT IS ALSO VERY IMPORTANT THAT THE 3 HEADERS ARE ADDED. Without these, even though you can plug the URL into a browser and get the visitor count returned, it won't work when accessed via JavaScript. This is because the JS used accesses the Lambda function as an AJAX request which isn't allowed by default. It'll throw a CORS error that doesn't make sense and is seemingly unrelated.

The code above doesn't accept any arguments, it's literally just an API call to trigger the Lambda to run. In the future I might rewrite it so I can do hits per article or something like that. For now it's just a home page traffic counter. It can be found on the home page, in the center aligned text above the articles, hidden as body color text. Select all text to view.