Python AWS DynamoDB
DynamoDB tables, items and queries through both the resource API and the low-level client.
Zato lets you work with Amazon DynamoDB directly from your Python services. You create an AWS connection in the Dashboard, and DynamoDB is available both through the low-level client under conn.dynamodb and through the higher-level resource API under conn.resource('dynamodb').
The resource API
For most day-to-day work, the resource API is the more convenient of the two - it accepts and returns plain Python values instead of DynamoDB's typed attribute format.
# -*- coding: utf-8 -*-
# Zato
from zato.server.service import Service
class SaveCustomer(Service):
input = 'customer_id', 'name'
def handle(self):
# Get the connection by its Dashboard name
conn = self.aws['My AWS']
# Get a handle to the table ..
dynamodb = conn.resource('dynamodb')
table = dynamodb.Table('customers')
# .. store the item ..
table.put_item(Item={
'customer_id': self.request.input.customer_id,
'name': self.request.input.name,
})
# .. and read it back.
response = table.get_item(Key={'customer_id': self.request.input.customer_id})
self.response.payload = response['Item']
The low-level client
The low-level client under conn.dynamodb maps one-to-one to the DynamoDB wire API, with explicit attribute types - S for strings, N for numbers, and so on.
# -*- coding: utf-8 -*-
# Zato
from zato.server.service import Service
class GetCustomer(Service):
input = 'customer_id'
def handle(self):
conn = self.aws['My AWS']
response = conn.dynamodb.get_item(
TableName='customers',
Key={'customer_id': {'S': self.request.input.customer_id}},
)
self.response.payload = response['Item']
Querying
# -*- coding: utf-8 -*-
# boto3
from boto3.dynamodb.conditions import Key
# Zato
from zato.server.service import Service
class GetCustomerOrders(Service):
input = 'customer_id'
def handle(self):
conn = self.aws['My AWS']
dynamodb = conn.resource('dynamodb')
table = dynamodb.Table('orders')
# All the orders of one customer, using the table's partition key
response = table.query(
KeyConditionExpression=Key('customer_id').eq(self.request.input.customer_id),
)
self.response.payload = {'orders': response['Items']}
Creating tables
# -*- coding: utf-8 -*-
# Zato
from zato.server.service import Service
class CreateCustomersTable(Service):
def handle(self):
conn = self.aws['My AWS']
conn.dynamodb.create_table(
TableName='customers',
KeySchema=[{'AttributeName': 'customer_id', 'KeyType': 'HASH'}],
AttributeDefinitions=[{'AttributeName': 'customer_id', 'AttributeType': 'S'}],
BillingMode='PAY_PER_REQUEST',
)