· 7 years ago · Jul 02, 2018, 12:38 AM
1import boto3
2from botocore.exceptions import ClientError
3
4
5DYNAMO = 'dynamodb'
6REGION = 'us-east-2'
7
8
9def create_dynamodb_table(table_name, access_key, secret_key, attributes, schema, provisions):
10 ''' This function takes a table name and key pair and returns a dynamodb
11 table. If the table already existed, it returns the existing table.
12 Otherwise, it creates a new table.
13 '''
14 dynamodb = get_dynamodb_connection(access_key,
15 secret_key)
16 try:
17 hashtag_table = create_table(dynamodb, table_name, attributes, schema, provisions)
18 except ClientError:
19 hashtag_table = dynamodb.Table(name=table_name)
20 return hashtag_table
21
22
23def get_dynamodb_connection(access_key, secret_key):
24 ''' This function takes an AWS key pair and returns a dynamodb connection.
25 '''
26 return boto3.resource(
27 DYNAMO,
28 region_name=REGION,
29 aws_access_key_id=access_key,
30 aws_secret_access_key=secret_key)
31
32
33def create_table(dynamodb, table_name, attributes, schema, provisions):
34 ''' This function tries to create a table in the provided dynamodb instance
35 with the provided hashtag as its name. Raises and error to the calling
36 function if the table already exists.
37
38 Example attributes:
39 [
40 {
41 'AttributeName': 'framework',
42 'AttributeType': 'S',
43 },
44 {
45 'AttributeName': 'unix_time',
46 'AttributeType': 'N',
47 }
48 ]
49 Example schema:
50 [
51 {
52 'AttributeName': 'framework',
53 'KeyType': 'HASH',
54 },
55 {
56 'AttributeName': 'unix_time',
57 'KeyType': 'RANGE',
58 }
59 ]
60 Example provisions:
61 {
62 'ReadCapacityUnits': 1,
63 'WriteCapacityUnits': 1,
64 }
65 '''
66 return dynamodb.create_table(
67 TableName=table_name,
68 AttributeDefinitions=attributes
69 KeySchema=schema
70 ProvisionedThroughput=provisions)