Python3: DynamoDB を使う


boto3 のインストール方法

Ubuntu 19.04

sudo apt install python3-boto3

city という名前のテーブルを作成

dynamo_create_table.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   dynamo_create_table.py
#
#                   Oct/7/2017
# --------------------------------------------------------------------
import sys
import boto3
#
sys.stderr.write("*** 開始 ***\n")

dynamodb = boto3.resource('dynamodb')

table = dynamodb.create_table(
    TableName='cities',
    KeySchema=[
        {
            'AttributeName': 'key',
            'KeyType': 'HASH'  #Partition key
        },
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'key',
            'AttributeType': 'S'
        },
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 30,
        'WriteCapacityUnits': 30
    }
)

print("Table status:", table.table_status)

sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

データの挿入

dynamo_insert.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   dynamo_insert.py
#
#                   Oct/7/2017
# ---------------------------------------------------------------
import  sys
import  boto3
from decimal import *
# ---------------------------------------------------------------
def insert_proc (key,name,population,date_mod):
    response = table.put_item ( \
    Item={'key': key,'name': name,'population': population,'date_mod':date_mod}
    )
# ---------------------------------------------------------------
sys.stderr.write ("*** 開始 ***\n")

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('cities')

insert_proc ("t0921","宇都宮",Decimal ("48219"),"2003-2-12")
insert_proc ("t0922","小山",Decimal ("79814"),"2003-5-24")
insert_proc ("t0923","佐野",Decimal ("69825"),"2003-7-27")

sys.stderr.write ("*** 終了 ***\n")
# ---------------------------------------------------------------

データのスキャン

dynamo_scan.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   dynamo_scan.py
#
#                   Oct/7/2017
# --------------------------------------------------------------------
import  sys
import  boto3
import  decimal
from boto3.dynamodb.conditions import Key, Attr

sys.stderr.write("*** 開始 ***\n")

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('cities')

response = table.scan()

for it in response['Items']:
    str_out = it['key'] + '\t'
    str_out += it['name'] + '\t'
    str_out += str (it['population']) + '\t'
    str_out += it['date_mod']
    print(str_out)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

キーを指定してデータの取得

dynamo_get.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   dynamo_get.py
#
#                   Oct/7/2017
# --------------------------------------------------------------------
import sys
import boto3
from boto3.dynamodb.conditions import Key, Attr

# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('cities')

key_search='t0922'

response = table.query(
    KeyConditionExpression=Key('key').eq(key_search)
)

for it in response['Items']:
    str_out = it['key'] + '\t'
    str_out += it['name'] + '\t'
    str_out += str (it['population']) + '\t'
    str_out += it['date_mod']
    print(str_out)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

キーを指定してデータの削除

dynamo_delete.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   dynamo_delete.py
#
#                   Oct/7/2017
# --------------------------------------------------------------------
import sys
import boto3
from boto3.dynamodb.conditions import Key

# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('cities')

key_search='t0922'

response = table.delete_item(
    Key={
            'key': key_search,
        }
)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

テーブルの削除

dynamo_delete_table.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   dynamo_delete_table.py
#
#                   Oct/7/2017
# --------------------------------------------------------------------
import  sys
import  boto3

sys.stderr.write("*** 開始 ***\n")
dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('cities')

table.delete()

sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

次のバージョンで確認しました。

$ python
Python 3.9.7 (default, Aug 31 2021, 13:28:12) 
[GCC 11.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> boto3.__version__
'1.18.34'