roe*_*gol 32 python amazon-dynamodb boto3
我是boto3中的新用户,我正在使用DynamoDB.
我经历了DynamoDB api,我找不到任何方法告诉我表是否已经存在.
处理此问题的最佳方法是什么?
我应该尝试创建一个新表并使用try catch包装它吗?
anu*_*ham 44
通过阅读文档,我可以看到有三种方法可以检查表是否存在.
ResourceInUseException.用try包装create_table方法除了捕获它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)
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)
如果您不想使用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)
您可以使用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)
您可以使用任何 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)
| 归档时间: |
|
| 查看次数: |
26959 次 |
| 最近记录: |