LoginSignup
3
6

More than 1 year has passed since last update.

Python3: DynamoDB を使う

Last updated at Posted at 2017-10-07

boto3 のインストール方法

Ubuntu 22.04

sudo apt install python3-boto3

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

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")
# ---------------------------------------------------------------

データのスキャン

この方法では、1MB 以上のデータは取得できません。

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_update.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	dynamo_update.py
#
#					Jul/22/2022
# --------------------------------------------------------------------
import sys
import datetime
import boto3
from boto3.dynamodb.conditions import Key, Attr

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

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('cities')

key_target = 't0922'
population_new = 34567210
date_mod = "%s" % datetime.date.today()

response = table.update_item(
	Key={
		'key': key_target
	},
	UpdateExpression="set population = :pp, date_mod = :dd",
	ExpressionAttributeValues= {
		':pp': population_new,
		':dd': date_mod
	},
	ReturnValues='UPDATED_NEW'
)

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

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.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> boto3.__version__
'1.20.34'
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6