Python 如何检查DynamoDB表是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42485616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:45:49  来源:igfitidea点击:

How to check if DynamoDB table exists?

pythonamazon-dynamodbboto3

提问by roeygol

I'm a new user in boto3 and i'm using DynamoDB.

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

I went through over the DynamoDB api and I couldn't find any method which tell me if a table is already exists.

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

What is the best approach dealing this issue?

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

Should I try to create a new table and wrap it using try catch ?

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

回答by anupsabraham

From reading the documentation, I can see that there are three methods by which you can check if a table exists.

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

  1. The CreateTable APIthrows an error ResourceInUseExceptionif the table already exists. Wrap the create_table method with try except to catch this
  2. You can use the ListTables APIto get the list of table names associated with the current account and endpoint. Check if the table name is present in the list of table names you get in the response.
  3. The DescribeTable APIwill throw an error ResourceNotFoundExceptionif the table name you request doesn't exist.
  1. CREATETABLE API抛出一个错误ResourceInUseException,如果该表已经存在。用 try 包裹 create_table 方法,但要抓住这个
  2. 您可以使用ListTables API获取与当前帐户和端点关联的表名称列表。检查您在响应中获得的表名列表中是否存在表名。
  3. 如果您请求的表名不存在,DescribeTable API将抛出错误ResourceNotFoundException

To me, the first option sounds better if you just want to create a table.

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

Edit:I see that some people are finding it difficult to catch the exceptions. I will put some code below for you to know how to handle exceptions in boto3.

编辑:我看到有些人发现很难捕获异常。我将在下面放一些代码让您了解如何处理 boto3 中的异常。

Example 1

示例 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

Example 2

示例 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,
    )

Example 3

示例 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

回答by anon58192932

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)

回答by notionquest

You can use describe tableAPI to determine whether the table exists.

您可以使用describe tableAPI 来判断表是否存在。

Sample code:

示例代码:

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)

If table exists:-

如果表存在:-

  • You will get the response
  • 你会得到回应

If table doesn't exists:-

如果表不存在:-

  • You will get ResourceNotFoundException

    botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotF oundException) when calling the DescribeTable operation: Cannot do operations on a non-existent table

  • 你会得到 ResourceNotFoundException

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

Another way:-

其它的办法:-

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.

等待直到此表存在。此方法调用轮询的 DynamoDB.Waiter.table_exists.wait()。DynamoDB.Client.describe_table() 每 20 秒执行一次,直到达到成功状态。检查失败 25 次后返回错误。

table.wait_until_exists()

回答by juggernaut

You can use .table_statusattr of any boto3 Table instance object. It returns it's status if exists (CREATING, UPDATING, DELETING, ACTIVE) or throws exception botocore.exceptions.ClientError: Requested resource not found: Table: <YOUR_TABLE_NAME> not found. You can wrap those conditions into try / except to have full info on the current table state.

您可以使用任何 boto3 Table 实例对象的.table_statusattr。如果存在(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

回答by ssc

Alternate approach if you do not want to use boto3.clientbut only boto3.resource:

如果您不想使用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')