CRUD DynamoDB from Python (boto3)

This post shows examples of DynamoDB usage from Python boto3.


install

% pip install boto3

% pip list | grep boto3

boto3                              1.17.61


test.py

import boto3


# connect to dynamodb (local)

# remove endpoint_url to use the cloud

dynamodb = boto3.resource('dynamodb', endpoint_url='http://localhost:8000')


# list table

table_list = dynamodb.tables.all()

for table in table_list:

  print(table.table_name)


# create table

table = dynamodb.create_table(

  TableName='student',

  AttributeDefinitions=[

    {

      'AttributeName': 'id',

      'AttributeType': 'S'

    },

  ],

  KeySchema=[

    {

      'AttributeName': 'id',

      'KeyType': 'HASH'

    }

  ],

  ProvisionedThroughput={

    'ReadCapacityUnits': 5,

    'WriteCapacityUnits': 5

  }

)

print(table) # dynamodb.Table(name='student')


# if you already have a table:

# table = dynamodb.Table('student')


# list table

table_list = dynamodb.tables.all()

for table in table_list:

  print(table.table_name)


# insert

response = table.put_item(

  Item = {

    'id': '001'

  }

)

print(response['ResponseMetadata']['HTTPStatusCode']) # 200


response = table.put_item(

  Item = {

    'id': '002',

    'grade': 'B'

  }

)

print(response['ResponseMetadata']['HTTPStatusCode']) # 200


# select

response = table.get_item(Key={'id': '002'})

print(response['Item']) # {'id': '002', 'grade': 'B'}


# update

response = table.update_item(

  Key={

    'id': '001'

  },

  UpdateExpression="set grade=:g",

  ExpressionAttributeValues={

    ':g': 'A'

  },

  ReturnValues="UPDATED_NEW"

)

print(response['Attributes']) # {'grade': 'A'}


# delete

response = table.delete_item(Key={'id': '001'})

print(response['ResponseMetadata']['HTTPStatusCode']) # 200


# drop table

response = table.delete()

print(response['ResponseMetadata']['HTTPStatusCode']) # 200


reference


Comments

Popular posts from this blog

Selenide: Quick Start

Minikube Installation for M1 Mac

Three.js Quick Start - Run Spinning-Cube Example