2017-02-27 152 views
8

我是boto3的新用户,我使用DynamoDB如何检查DynamoDB表是否存在?

我翻阅了DynamoDB api,找不到任何告诉我表是否已存在的方法。

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

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

回答

12

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

  1. 如果该表已存在,则CreateTable API将引发错误ResourceInUseException。使用try来包装create_table方法,除了捕获这个
  2. 您可以使用ListTables API来获取与当前帐户和端点关联的表名称列表。检查表名是否出现在响应中获取的表名列表中。
  3. 如果您请求的表名称不存在,DescribeTable API将引发错误ResourceNotFoundException

对我来说,如果你只是想创建一个表,第一个选项听起来会更好。

编辑: 我看到有些人发现很难捕捉到例外。我将在下面放置一些代码,以了解如何处理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 = 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 
3

您可以使用描述表 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操作时:不能做 操作的不存在的表

另一种方式: -

Waits until this Table is exists. This method calls DynamoDB.Waiter.table_exists.wait() which polls. DynamoDB.Client.describe_table() every 20 seconds until a successful state is reached. An error is returned after 25 failed checks.

table.wait_until_exists() 
+3

我喜欢你的代码,但不知道如何导入'botocore.errorfactory.ResourceNotFoundException'。我不断收到'AttributeError:'模块'对象没有属性'ResourceNotFoundException'。我输入了'boto3'和'botocore'。 – anon58192932

+0

@ anon58192932你弄清楚如何导入该异常?我面临同样的问题。 – Phito

+1

@人为抱歉,我刚回到工作。请看我的回答,我将发布如何检查例外。据我所知,它不能直接导入。 – anon58192932

7
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) 
+1

谢谢!我失去了我的头发。 – mmr

2

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

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