Soy un usuario nuevo en boto3 y estoy usando DynamoDB .
Revisé la API de DynamoDB y no pude encontrar ningún método que me dijera si ya existe una tabla.
¿Cuál es el mejor enfoque para tratar este problema?
¿Debería intentar crear una nueva tabla y envolverla usando try catch?
Al leer la documentación, puedo ver que hay tres métodos mediante los cuales puede verificar si existe una tabla.
ResourceInUseException si la tabla ya existe. Envuelva el método create_table con try excepto para capturar estoResourceNotFoundException si el nombre de la tabla que solicita no existe.Para mí, la primera opción suena mejor si solo quieres crear una tabla.
Editar: Veo que a algunas personas les resulta difícil detectar las excepciones. Pondré un código a continuación para que sepas cómo manejar las excepciones en boto3.
Ejemplo 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 passEjemplo 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, )Ejemplo 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 passimport 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)Enfoque alternativo si no desea utilizar boto3.client sino solo 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')