SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Development resources, articles, tutorials, code samples, tools and downloads for AWS Amazon Web Services, Redshift, AWS Lambda Functions, S3 Buckets, VPC, EC2, IAM

Create DynamoDB Table using Python Code


Using sample Python codes shared in this Amazon DynamoDB tutorial, data engineers can build their cloud applications on AWS by creating DynamoDB tables easily. Amazon DynamoDB is a fully managed NoSQL database from AWS which provides globally distributed fully managed NoSQL key-value database platform on AWS cloud platform for application developers.

I plan this tutorial in multiple steps. In this first guide, I will share sample Python codes required to create an Amazon DynamoDB table.
In following tutorials, I will also share Python code samples to populate sample DynamoDB table with data read from a json file.


Sample Python Code for Creating Amazon DynamoDB Table

Below Python code example can be executed to create a DynamoDB. This sample code in our tutorial creates a table named Movies whose configuration details are read from a configuration file named tables.ini

First of all, the Python code starts creating an instance of the boto3 dynamodb client object.
Then the newly created dynamodb client object is passed to the main routine where all following tasks take place within this main function.
In main function we first read the configuration details of the NoSQL DynamoDB table by parsing values for the specific Movies table from the configuration file tables.ini
Then create_table() method is executed in createTable function with required populated parameters in order to create the DynamoDB table movies.
Using the appropriate wait function, a success or fail response is waited from the DynamoDB service.
And finally as a validation, the response from a successful table creation task is read.

import boto3
import botocore
import configparser



def main(ddbClient):

 config = readConfig()
 tableDefinition = {
  'tableName': config['tableName'],
  'partitionKey': config['partitionKey'],
  'sortKey': config['sortKey'],
  'readCapacity': config['readCapacity'],
  'writeCapacity': config['writeCapacity'],
 }

 creationResponse = createTable(ddbClient, tableDefinition)
 waitForTableCreation(ddbClient, config['tableName'])
 tableOutput = getTableInfo(ddbClient, config['tableName'])


def createTable(ddbClient, tableDefinition):
 response = ddbClient.create_table(
  AttributeDefinitions=[
   {
    'AttributeName': tableDefinition["partitionKey"],
    'AttributeType': 'S',
   },
   {
    'AttributeName': tableDefinition["sortKey"],
    'AttributeType': 'S',
   },
  ],
  KeySchema=[
   {
    'AttributeName': tableDefinition["partitionKey"],
    'KeyType': 'HASH',
   },
   {
    'AttributeName': tableDefinition["sortKey"],
    'KeyType': 'RANGE',
   },
  ],
  ProvisionedThroughput={
   'ReadCapacityUnits': int(tableDefinition["readCapacity"]),
   'WriteCapacityUnits': int(tableDefinition["writeCapacity"]),
  },
  TableName=tableDefinition["tableName"]
 )

 return response


def waitForTableCreation(ddbClient, tableName):
 waiter = ddbClient.get_waiter('table_exists')
 waiter.wait(TableName=tableName)


def getTableInfo(ddbClient, tableName):
 response = ddbClient.describe_table(TableName=tableName)
 return response


def readConfig():
 config = configparser.ConfigParser()
 config.read('./tables.ini')

 return config['Movies']


client = boto3.client('dynamodb')

try:
 main(client)
except botocore.exceptions.ClientError, err:
 print err.response['Error']['Message']
except botocore.exceptions.ParamValidationError, error:
 print error

Since within the root routine all code is wrapped within a Try-Catch block, all exceptions caused from any kind of error is catched and error is displayed on the screen with a print command.

Besides the above Python code sample, I am also sharing a configuration file sample for this tutorial.
The configuration file can be used for keeping detailed information like partition key, sort key of multiple DynamoDB tables.
The configuration section for a specific NoSQL table for DynamoDB is read by using ConfigParser() method.

[Movies]
tableName = Movies
partitionKey = Title
sortKey = ReleaseDate
readCapacity = 6
writeCapacity = 6
datafile = ./movies.json
pageSize = 3
[Cineaste]
tableName = Cineaste
partitionKey = Title
sortKey = Duty
readCapacity = 6
writeCapacity = 6
datafile = ./cineaste.json
pageSize = 3

When you save the above Python code in a .py file and run it, the sample DynamoDB table Movies will be created.

create DynamoDB table using Python code

In addition to the configuration details of each DynamoDB table, I also added sample data in JSON format in a separate .json file.
Application developers can use the sample data and load for their tests.
In later steps in a separate DynamoDB with Python tutorial, I will also share codes to upload data from json files.

Below screenshot is taken from AWS Management Console DynamoDB dashboard showing Movies table content created in this AWS tutorial.

sample Movies DynamoDB table contents queried on AWS Management Console



AWS


Copyright © 2004 - 2024 Eralper YILMAZ. All rights reserved.