如何检查DynamoDB表是否存在?

时间:2017-02-27 12:16:04

标签: python amazon-dynamodb boto3

我是boto3中的新用户,我正在使用DynamoDB

我浏览了DynamoDB api,我找不到任何方法告诉我表是否已经存在。

处理此问题的最佳方法是什么?

我应该尝试创建一个新表并使用try catch包装它吗?

6 个答案:

答案 0 :(得分:40)

通过阅读文档,我可以看到有三种方法可以检查表是否存在。

  1. 如果表已存在,则CreateTable API会引发错误ResourceInUseException。使用try包装create_table方法除了捕获此
  2. 您可以使用ListTables API获取与当前帐户和端点关联的表名列表。检查表名是否出现在响应中的表名列表中。
  3. 如果您请求的表格名称不存在,DescribeTable API将抛出错误ResourceNotFoundException
  4. 对我来说,如果你只想创建一个表,第一个选项听起来会更好。

    修改 我看到有些人发现难以捕捉异常。我将在下面提供一些代码,以便您了解如何处理boto3中的异常。

    示例1

    import boto3
    
    dynamodb_client = boto3.client('dynamodb')
    
    try:
        response = dynamodb_client.create_table(
            AttributeDefinitions=[
                {
                    'AttributeName': 'Artist',
                    'AttributeType': 'S',
                },
                {
                    'AttributeName': 'SongTitle',
                    'AttributeType': 'S',
                },
            ],
            KeySchema=[
                {
                    'AttributeName': 'Artist',
                    'KeyType': 'HASH',
                },
                {
                    'AttributeName': 'SongTitle',
                    'KeyType': 'RANGE',
                },
            ],
            ProvisionedThroughput={
                'ReadCapacityUnits': 5,
                'WriteCapacityUnits': 5,
            },
            TableName='test',
        )
    except dynamodb_client.exceptions.ResourceInUseException:
        # do something here as you require
        pass
    

    示例2

    import boto3
    
    dynamodb_client = boto3.client('dynamodb')
    
    
    table_name = 'test'
    existing_tables = dynamodb_client.list_tables()['TableNames']
    
    if table_name not in existing_tables:
        response = dynamodb_client.create_table(
            AttributeDefinitions=[
                {
                    'AttributeName': 'Artist',
                    'AttributeType': 'S',
                },
                {
                    'AttributeName': 'SongTitle',
                    'AttributeType': 'S',
                },
            ],
            KeySchema=[
                {
                    'AttributeName': 'Artist',
                    'KeyType': 'HASH',
                },
                {
                    'AttributeName': 'SongTitle',
                    'KeyType': 'RANGE',
                },
            ],
            ProvisionedThroughput={
                'ReadCapacityUnits': 5,
                'WriteCapacityUnits': 5,
            },
            TableName=table_name,
        )
    

    示例3

    import boto3
    
    dynamodb_client = boto3.client('dynamodb')
    
    try:
        response = dynamodb_client.describe_table(TableName='test')
    except dynamodb_client.exceptions.ResourceNotFoundException:
        # do something here as you require
        pass
    

答案 1 :(得分:10)

import boto3

from botocore.exceptions import ClientError

TABLE_NAME = "myTableName"
dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")

table = dynamodb.Table(TABLE_NAME)

try:
    response = client.describe_table(TableName=TABLE_NAME)

except ClientError as ce:
if ce.response['Error']['Code'] == 'ResourceNotFoundException':
    print "Table " + TABLE_NAME + " does not exist. Create the table first and try again."
else:
    print "Unknown exception occurred while querying for the " + TABLE_NAME + " table. Printing full error:"
    pprint.pprint(ce.response)

答案 2 :(得分:4)

您可以使用 describe table API来确定表是否存在。

示例代码:

from __future__ import print_function # Python 2/3 compatibility
import os
os.environ["TZ"] = "UTC"
import boto3

client = boto3.client('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")



response = client.describe_table(
    TableName='Movies'
)    

print(response)

如果表存在: -

  • 您将收到回复

如果表格不存在: -

  • 您将获得ResourceNotFoundException

    botocore.errorfactory.ResourceNotFoundException:发生错误(ResourceNotF oundException)调用DescribeTable操作时:无法对其进行操作  一张不存在的表格

另一种方式: -

  

等待此表存在。这个方法叫   轮询的DynamoDB.Waiter.table_exists.wait()。   DynamoDB.Client.describe_table()每20秒一次成功   达到了国家。检查失败25次后返回错误。

table.wait_until_exists()

答案 3 :(得分:2)

您可以使用任何boto3 Table实例对象的.table_status attr。如果存在(CREATING,UPDATING,DELETING,ACTIVE)或抛出异常botocore.exceptions.ClientError: Requested resource not found: Table: <YOUR_TABLE_NAME> not found,它将返回其状态。您可以将这些条件包装到try / except中,以获得有关当前表状态的完整信息。

import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
table = dynamodb.Table('your_table_name_str')

try:
  is_table_existing = table.table_status in ("CREATING", "UPDATING",
                                             "DELETING", "ACTIVE")
except ClientError:
  is_table_existing = False
  print "Table %s doesn't exist." % table.name

答案 4 :(得分:1)

如果您不想使用boto3.client而是仅使用boto3.resource的替代方法:

import boto3

database = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")    

table_name  = 'MyTable'
table_names = [table.name for table in database.tables.all()]

if table_name in table_names:
    print('table', table_name, 'exists')

答案 5 :(得分:1)

请注意,这取决于您使用的是客户端还是资源。如果使用<mat-form-field>,则可以使用3种方法接受建议的答案。如果您使用的是boto3.client(),则只能使用boto3.resource()并检查异常。

dynamodb_resource.create_table()