AWS DynamoDB with Python

Another way to use DynamoDB


Published on: March 29, 2020

Lessons from my work project

Feature creep and unexpected changes are quite common from my work experience. We had to switch to a different library to read and process Excel after the requirements changed to using a different type of workbook. The library I found that would help was in Python so I thought a fun and necessary exercise was to change the previous JS lambda to a Python.

Do the necessary imports

import boto3

dynamodb = boto3.resource('dynamodb')
data_table = dynamodb.Table(<table name>)

Batch writing (Cuts execution time by HALF)

result_data = [<list of Items to populate in DB>]
with data_table.batch_writer() as loader:
    for Item in result_data:
       response=loader.put_item(
          Item=Item
       )
    return json.dumps(response)

Batch GET

client = boto3.client('dynamodb')
res = client.batch_get_item(
     RequestItems = {
       '<table name>': {
          'Keys': [
            {
              '<Primary Key for Item>': {
                 '<type of Primary Key> S | B | H': <value>
              }
            },
            ...rest of Items you want to batch GET
          ],
          'ProjectionExpression': '<Primary Key>, <rest of Item attributes you want to get>'
       }
     }
   )

print(res['Responses'])

Example Batch GET

client = boto3.client('dynamodb')
res = client.batch_get_item(
     RequestItems = {
       'music': {
          'Keys': [
            {
              'ReferenceID': {
                 'S': '7706-02'
              }
            },
            {
              'ReferenceID': {
                 'S': '7706-02335'
              }
            },
            {
              'ReferenceID': {
                 'S': '7706-033352'
              }
            },
          ],
          'ProjectionExpression': 'ReferenceID, Name, UpdatedAt'
       }
     }
   )

print(res['Responses'])