首先,需要在 docker-compose.yml
文件中添加DYNAMODB_CREATE_TABLES=true
来创建DynamoDB表。
然后在创建DynamoDB表的代码中,需要使用boto3.client()
函数,将endpoint_url
参数设为localstack的地址。代码示例如下:
import boto3
import os
if os.environ.get('LOCALSTACK_HOSTNAME'):
dynamodb = boto3.client('dynamodb',
endpoint_url='http://%s:4569' % os.environ['LOCALSTACK_HOSTNAME'])
else:
dynamodb = boto3.client('dynamodb')
def create_dynamodb_table():
table_name = 'your_table_name'
dynamodb.create_table(
TableName=table_name,
KeySchema=[
{
'AttributeName': 'partition_key',
'KeyType': 'HASH'
},
{
'AttributeName': 'sort_key',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'partition_key',
'AttributeType': 'S'
},
{
'AttributeName': 'sort_key',
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 10,
'WriteCapacityUnits': 10
}
)
return table_name
最后执行创建表的函数,即可在localstack中创建全局DynamoDB表。