DynamoDB

It's great to have a form that's sending us data now, but it's of limited use unless we can store the data for later. In the context of our AWS Lambda-based app, DynamoDB is a good option for storing our application data, for three main reasons:

  1. we don't have to allocate a persistent server to run it,
  2. it's easily accessible using the Python boto3 library, and
  3. it's got a nice free tier that never goes away.

DynamoDB is a key-value/document database — the data is not structured like in a traditional relational database. Each 'document' is a collection of one or more key/value pairs (like a JSON document), where one of the keys is a 'partition key'. You can also add an optional 'sort key'. You can read the DynamoDB documentation here. For our purposes we'll generate one table that will contain author records, including emails, bios, and app metadata.

Generating a DynamoDB table in the AWS web console is straightforward, you can start here.

Amazon provides excellent API documentation that describes how to interface to DynamoDB tables using Python. Here's the way we'll be doing it in our app:

import boto3

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table('your_dynamo_table')

table_item = {
            'author_email': email,
            'bio': bio
        }

table.put_item(Item=table_item)

As you can see, it's simple to add a new document to our table. The table name is your_dynamo_table, and we're adding a item with just two values, an email and a bio string. Editing an existing item can be slightly more tricky, but not too bad:

table.update_item(Key={'author_email': email},
           UpdateExpression="SET bio = :bio",
           ExpressionAttributeValues={":bio":userbio})

Key is the Dynamo partition key, which in this case is author_email. The partition key is determined at the time of table generation. The non-primary key bio is the value we want to change, and we do it via the two parameters UpdateExpression and ExpressionAttributeValues.

Now we can put it all together! In the git repo, check out the index function in the profile-app.py file to see a fully-functioning example with a few bells and whistles added.


If you're finding this guide useful, you may want to sign up to receive more of my writing at cloudconsultant.dev.