Friday, June 19, 2020

AWS DynamoDB + Python

AWS DynamoDB with Python

Create a DynamoDB table as follows:

Table name: TestTable
Primary partition key: TestID (String)

There are two functions.

The updateTable is to update if the key item is found or add if the key is NOT found. It will add the Nickname "column" if it's not already there.

The getContent is to retrieve all content from the table where the nickname is not 'Frank'. The return line also has a condition that if it's empty then return an empty list.  FilterExpression supports various comparison operators including, 'eq' for 'equals'; 'lt' for 'less than'; or 'lte' for 'less than or equal to'

import boto3
from boto3.dynamodb.conditions import Key, Attr
profile = "default"
session = boto3.Session(profile_name=profile)
thisRegion = "us-east-1"
thisResource = session.resource('dynamodb', region_name=thisRegion)

def updateTable(thisId,name):
    table = thisResource.Table('TestTable')
    response = table.update_item(
        Key={
            'TestID': thisId
        },
        UpdateExpression='set Nickname = :nickname',
        ExpressionAttributeValues={
            ':nickname': name
        },
        ReturnValues="UPDATED_NEW"
    )

def getContent(filterString):
    table = thisResource.Table('TestTable')
    response = table.scan(
        FilterExpression=Attr('Nickname').ne(filterString)
    )
    return(response.get('Items',[]))

updateTable('111111','Joe')
updateTable('111121','Frank')
updateTable('111131','Hank')
getContent(filterString='Frank')

Result:

[{'TestID': '111111', 'Nickname': 'Joe'},
 {'TestID': '111131', 'Nickname': 'Hank'}]

No comments:

Post a Comment

AWS WAF log4j query

How to query AWS WAF log for log4j attacks 1. Setup your Athena table using this instruction https://docs.aws.amazon.com/athena/latest/ug/wa...