1、安装boto3
pip install boto3
python -m pip install boto3
2、dynamodb使用
官方例子:Amazon DynamoDB — Boto3 Docs 1.24.60 documentation
#! /usr/bin/env python
#coding=utf-8
import boto3
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
table_name = "alan_test"
def print_item(item):
# id
id_ = item['id'] if 'id' in item else 0
# name
name_ = item['name'] if 'name' in item else ''
# age
age_ = item['age'] if 'age' in item else 0
# class
class_ = item['class'] if 'class' in item else 0
print("id: %s, name: %s, age: %s, class: %s" % (id_, name_, age_, class_))
def run():
# init dynamodb
if(raw_input("init dynamodb: [y/n]") != 'y'):
return
session_args = {} # Found credentials in ~/.aws/credentials [default]
#session_args = {'profile_name': 'alan'}
#session_args = {
# 'aws_access_key_id': 'A1b1C1',
# 'aws_secret_access_key': 'A+B2c2',
#}
session = boto3.session.Session(**session_args)
dynamodb = session.resource('dynamodb', region_name='cn-northwest-1') # region_name 使用哪个区域的aws服务
# dynamodb = session.resource('dynamodb', region_name='cn-northwest-1', endpoint_url='http://localhost:8000') # endpoint_url dynamodb位置
# list table
if(raw_input("list table: [y/n]") != 'y'):
return
for table in dynamodb.tables.all():
print(table.name)
# create table
if(raw_input("create table: [y/n]") != 'y'):
return
try:
dynamodb.create_table(
TableName=table_name, # 表名
KeySchema=[ # 主键
{
'AttributeName': 'id',
'KeyType': 'HASH' # Partition key 分区键
},
{
'AttributeName': 'name',
'KeyType': 'RANGE' # Sort key 排序键
}
],
AttributeDefinitions=[ # 主键数据类型
{
'AttributeName': 'id',
'AttributeType': 'N' # Number
},
{
'AttributeName': 'name',
'AttributeType': 'S' # String
},
],
BillingMode='PAY_PER_REQUEST',
Tags=[
{
"Key": "Owner",
"Value": "alan"
}
]
)
# Wait until the table exists.
dynamodb.Table(table_name).meta.client.get_waiter(
'table_exists').wait(TableName=table_name)
except Exception, e:
print('failed to create table [%s].' % table_name)
# check table
if(raw_input("check table: [y/n]") != 'y'):