如何检查DynamoDB表是否存在?

roe*_*gol 32 python amazon-dynamodb boto3

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

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

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

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

anu*_*ham 44

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

  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
Run Code Online (Sandbox Code Playgroud)

例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,
    )
Run Code Online (Sandbox Code Playgroud)

例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
Run Code Online (Sandbox Code Playgroud)

  • 那是因为你使用的是服务资源而不是客户端.检查代码中的这一行:`dynamodb_client = boto3.client('dynamodb')` (3认同)
  • 使用“describe_table”,我得到“AttributeError:'dynamodb.ServiceResource”对象没有属性“describe_table”。 (2认同)
  • 所描述的异常处理将与客户端 API 一起使用,但是是否有办法从资源 API 捕获异常?例如 `boto3.resource("dynamodb").Table("table_that_doesnt_exist")` 将引发 `ResourceNotFoundException` 但我无法捕获此用例。 (2认同)

ano*_*932 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)
Run Code Online (Sandbox Code Playgroud)

  • 这次真是万分感谢!我失去了留下的头发. (2认同)

ssc*_*ssc 8

如果您不想使用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')
Run Code Online (Sandbox Code Playgroud)


not*_*est 7

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

如果表存在:-

  • 你会得到回应

如果表不存在:-

  • 你会得到 ResourceNotFoundException

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

其它的办法:-

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

table.wait_until_exists()
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢你的代码,但不知道如何导入 `botocore.errorfactory.ResourceNotFoundException`。我不断收到`AttributeError: 'module' object has no attribute 'ResourceNotFoundException'`。我导入了 `boto3` 和 `botocore`。 (5认同)

jug*_*aut 5

您可以使用任何 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
Run Code Online (Sandbox Code Playgroud)