在创建 DynamoDB 表时,AWS 提供了一个以 JSON 格式指定表的方法。但是,在使用 Localstack 模拟 AWS 环境时,可能会遇到无法从 JSON 创建 DynamoDB 表的问题。
解决此问题的一个简单方法是手动编写代码来创建 DynamoDB 表。以下是一个示例代码,可以在 Python 中使用:
import boto3
from localstack.utils.aws import aws_stack
ddb = aws_stack.connect_to_service('dynamodb')
table_name = 'my-table'
key_schema = [{
'AttributeName': 'my-partition-key',
'KeyType': 'HASH'
}]
attribute_definitions = [{
'AttributeName': 'my-partition-key',
'AttributeType': 'S'
}]
billing_mode = 'PAY_PER_REQUEST'
ddb.create_table(TableName=table_name,
KeySchema=key_schema,
AttributeDefinitions=attribute_definitions,
BillingMode=billing_mode)
此代码使用 Localstack 提供的 aws_stack 功能来连接 DynamoDB 服务。然后,使用 create_table() 方法创建表,并指定表的名称、主键方案、属性定义和计费模式。
这样,就可以在 Localstack 模拟环境中成功创建 DynamoDB 表了。