Python and DynamoDB
In this tutorial, you use the AWS SDK for Python (Boto 3) to write simple programs to perform the following Amazon DynamoDB operations:
- Install DynamoDB Local
- Table Creation for DynamoDB Local
- Perform create, read, update, and delete operations on the table.
- Run simple queries.
Getting started with Boto 3 is easy, but requires a few steps.
1. Install Plugin
npm install -g serverless
2. Installation Boto3
Install the latest Boto 3 release via pip:
pip install boto3
You may also install a specific version:
pip install boto3==1.0.0
3. Install aws CLI
pip install awscli — upgrade — user
4. Configuration
Before you can begin using Boto 3, you should set up authentication credentials. Credentials for your AWS account can be found in the IAM Console. You can create or use an existing user. Go to manage access keys and generate a new set of keys.
If you have the AWS CLI installed, then you can use it to configure your credentials file:
aws configure
Alternatively, you can create the credential file yourself. By default, its location is at ~/.aws/credentials:
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY
You may also want to set a default region. This can be done in the configuration file. By default, its location is at ~/.aws/config:
region=us-east-1
Alternatively, you can pass a region_name when creating clients and resources.
5. Using Boto 3
To use Boto 3, you must first import it and tell it what service you are going to use:
import boto3# Let's use Amazon dynamodb
client = boto3.client('dynamodb'))
5. 1 Creating a New Table
In order to create a new table, use the DynamoDB.ServiceResource.create_table() method
import boto3
# Get the service resource.
dynamodb = boto3.resource('dynamodb')
# Create the DynamoDB table.
table = dynamodb.create_table(
TableName='users',
KeySchema=[
{
'AttributeName': 'username',
'KeyType': 'HASH'
},
{
'AttributeName': 'last_name',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'username',
'AttributeType': 'S'
},
{
'AttributeName': 'last_name',
'AttributeType': 'S'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
# Wait until the table exists.
table.meta.client.get_waiter('table_exists').wait(TableName='users')
# Print out some data about the table.
print(table.item_count)
This creates a table named users that respectively has the hash and range primary keys username and last_name. This method will return a DynamoDB.Table resource to call additional methods on the created table.
5.2 Using an Existing Table
It is also possible to create a DynamoDB.Table resource from an existing table:
import boto3# Get the service resource.
dynamodb = boto3.resource('dynamodb')# Instantiate a table resource object without actually
# creating a DynamoDB table. Note that the attributes of this table
# are lazy-loaded: a request is not made nor are the attribute
# values populated until the attributes
# on the table resource are accessed or its load() method is called.table = dynamodb.Table('users')# Print out some data about the table.
# This will cause a request to be made to DynamoDB and its attribute
# values will be set based on the response.
print(table.creation_date_time)
Expected Output (Please note that the actual times will probably not match up):
2015-06-26 12:42:45.149000-07:00
5.3 Creating a New Item
Once you have a DynamoDB.Table resource you can add new items to the table using DynamoDB.Table.put_item():
table.put_item(
Item={
'username': 'janedoe',
'first_name': 'Jane',
'last_name': 'Doe',
'age': 25,
'account_type': 'standard_user',
}
)
For all of the valid types that can be used for an item, refer to Valid DynamoDB Types.
5.4 Getting an Item
You can then retrieve the object using DynamoDB.Table.get_item():
response = table.get_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
}
)
item = response['Item']
print(item)
Expected Output:
{u'username': u'janedoe',
u'first_name': u'Jane',
u'last_name': u'Doe',
u'account_type': u'standard_user',
u'age': Decimal('25')}
5.5 Updating Item
You can then update attributes of the item in the table:
table.update_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
},
UpdateExpression='SET age = :val1',
ExpressionAttributeValues={
':val1': 26
}
)
Then if you retrieve the item again, it will be updated appropriately:
response = table.get_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
}
)
item = response['Item']
print(item)
Expected Output:
{u'username': u'janedoe',
u'first_name': u'Jane',
u'last_name': u'Doe',
u'account_type': u'standard_user',
u'age': Decimal('26')}
5.6 Deleting Item
You can also delete the item using DynamoDB.Table.delete_item():
table.delete_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
}
)
5.7 Deleting a Table
Finally, if you want to delete your table call DynamoDB.Table.delete():
table.delete()