Creating a DynamoDB table using Python

Here is generic Python code to create a table. Create a Python script called dynamo_table_creation.py with the following code:

import boto3

def create_dynamo_table(table_name_value, enable_streams=False,
                        read_capacity=1,
                        write_capacity=1,
                        region='eu-west-1'):
    table_name = table_name_value
    print('creating table: ' + table_name)
    try:
        client = boto3.client(service_name='dynamodb', 
region_name=region) print(client.create_table(TableName=table_name, AttributeDefinitions=[{'AttributeName': 'EventId', 'AttributeType': 'S'}, {'AttributeName': 'EventDay', 'AttributeType': 'N'}], KeySchema=[{'AttributeName': 'EventId', 'KeyType': 'HASH'}, {'AttributeName': 'EventDay', 'KeyType': 'RANGE'}, ], ProvisionedThroughput={'ReadCapacityUnits': read_capacity, 'WriteCapacityUnits': write_capacity})) except Exception as e: print(str(type(e))) print(e.__doc__) def main(): table_name = 'user-visits' create_dynamo_table(table_name, False, 1, 1) if __name__ == '__main__': main()

Rather than creating a DynamoDB table in the AWS Console, here, we are creating it using the Python SDK Boto3. main() calls the method called create_dynamo_table(), which takes various parameters associated with the table we are going to create, table_name being the first. Ignore the enable_streams parameter, which we will use later. The other two are linked to the initial read and write capacities. These will have a direct impact on the costs, along with the table size and the data retrieved. That is why I have set them to 1 by default. The region parameter should be your AWS region.

We then create a boto3.client(), which is a low-level client representing DynamoDB. We then use this to create a table using client.create_table(), passing in the parameters passed in to our create_dynamo_table(), along with the partition key name, EventId, with its data type, String, indicated by S, and sort key name, EventDay, with its data type number indicated as N. All other attributes will be optional and arbitrary.

You will notice a change in key terminology in DynamoDB between the Management Console and Boto3 descriptions, but they are synonyms: Partition key (AWS Console) = Hash key (Boto3) and Sort key (AWS Console) = Range key (Boto3).

Both together, as a composite key, are called a primary key.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset