在这篇文章中,我们将探讨如何使用 Python 的 Boto3 库来创建一个 Amazon DynamoDB 表。DynamoDB 是一个快速且灵活的 NoSQL 数据库服务,适合处理大量数据,并提供单数毫秒级的响应时间。
什么是 Boto3?
Boto3 是 AWS 的官方 SDK,它允许 Python 开发者轻松地与 AWS 服务进行交互。通过 Boto3,我们可以编写代码来创建、配置和管理 AWS 资源,包括 DynamoDB。
前提条件
在开始之前,请确保你已经安装了 Boto3 和配置了 AWS 凭证。如果你还没有安装 Boto3,可以通过 pip 安装:
pip install boto3
确保你的 AWS 凭证(AWS Access Key ID 和 Secret Access Key)已经配置在你的环境变量中,或者使用 AWS CLI 配置文件。
aws configure
# 举例:
AWS Access Key ID [***]: 你的AWS AK
AWS Secret Access Key [***]:你的AWS SK
Default region name [us-east-1]:你的AWS 所在区域
Default output format [None]:
步骤 1: 导入 Boto3 库并创建 DynamoDB 客户端
import boto3
# 创建 DynamoDB 客户端
dynamodb = boto3.resource('dynamodb', region_name='your-region')
请将 'your-region'
替换为你的 AWS 区域。举例:'us-east-1'
美国东部(弗吉尼亚州北部)
AWS区域表:区域和可用区 - Amazon Elastic Compute Cloud
步骤 2: 定义表的属性
我们定义表的属性,包括表名、主键。
table_name = 'demo-table'
table = dynamodb.create_table(
TableName=table_name,
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH' # Partition key
}
],
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S' # String
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
在这个例子中,我们创建了一个名为 YourSimpleTableName
的表,它有一个字符串类型的分区键 id
。
步骤 3: 等待表创建完成(可以不要)
创建表是一个异步操作,所以我们需要等待表变为 ACTIVE
状态。
table.meta.client.get_waiter('table_exists').wait(TableName=table_name)
print(f"Table {table_name} is now active.")
步骤 4: 检查表的状态(可以不要)
在继续之前,检查表的状态以确保它已经创建成功。
table_status = table.table_status
print(f"Table status: {table_status}")
完整代码:
创建create_dynamodb_table.py文件,并写入以下内容
import boto3
# 创建 DynamoDB 服务资源
dynamodb = boto3.resource('dynamodb', region_name='your-region')
# 定义表名
table_name = 'YourSimpleTableName'
# 创建表
table = dynamodb.create_table(
TableName=table_name,
KeySchema=[
{'AttributeName': 'id', 'KeyType': 'HASH'} # 分区键
],
AttributeDefinitions=[
{'AttributeName': 'id', 'AttributeType': 'S'} # 定义属性类型
],
ProvisionedThroughput={
'ReadCapacityUnits': 5, # 预置读吞吐量
'WriteCapacityUnits': 5 # 预置写吞吐量
}
)
# 等待表变为 ACTIVE 状态(可以不要)
table.meta.client.get_waiter('table_exists').wait(TableName=table_name)
print(f"Table {table_name} is now active.")
# 检查表的状态(可以不要)
table_status = table.table_status
print(f"Table status: {table_status}")
运行脚本:
python create_dynamodb_table.py
总结
使用 Boto3 创建一个简单的 DynamoDB 表是直接且快速的。上述代码展示了如何创建一个只有 id
作为主键的表,并且可以存储 name
作为附加属性。你可以根据需要调整读写吞吐量和其他配置。希望这篇文章能帮助你熟悉和开始使用 DynamoDB 和 Boto3。