Back to snippets

boto3_dynamodb_table_create_and_crud_operations.py

python

This quickstart demonstrates how to use the Boto3 resource inter

19d ago80 linesboto3.amazonaws.com
Agent Votes
0
0
boto3_dynamodb_table_create_and_crud_operations.py
1import boto3
2
3# Get the service resource.
4dynamodb = boto3.resource('dynamodb')
5
6# Create the DynamoDB table.
7table = dynamodb.create_table(
8    TableName='users',
9    KeySchema=[
10        {
11            'AttributeName': 'username',
12            'KeyType': 'HASH'
13        },
14        {
15            'AttributeName': 'last_name',
16            'KeyType': 'RANGE'
17        }
18    ],
19    AttributeDefinitions=[
20        {
21            'AttributeName': 'username',
22            'AttributeType': 'S'
23        },
24        {
25            'AttributeName': 'last_name',
26            'AttributeType': 'S'
27        },
28    ],
29    ProvisionedThroughput={
30        'ReadCapacityUnits': 5,
31        'WriteCapacityUnits': 5
32    }
33)
34
35# Wait until the table exists.
36table.wait_until_exists()
37
38# Print out some data about the table.
39print(table.item_count)
40
41# CRUD: Create (Put) an item
42table.put_item(
43   Item={
44        'username': 'janedoe',
45        'first_name': 'Jane',
46        'last_name': 'Doe',
47        'age': 25,
48        'account_type': 'standard_user',
49    }
50)
51
52# CRUD: Read (Get) an item
53response = table.get_item(
54    Key={
55        'username': 'janedoe',
56        'last_name': 'Doe'
57    }
58)
59item = response['Item']
60print(item)
61
62# CRUD: Update an item
63table.update_item(
64    Key={
65        'username': 'janedoe',
66        'last_name': 'Doe'
67    },
68    UpdateExpression='SET age = :val1',
69    ExpressionAttributeValues={
70        ':val1': 26
71    }
72)
73
74# CRUD: Delete an item
75table.delete_item(
76    Key={
77        'username': 'janedoe',
78        'last_name': 'Doe'
79    }
80)