Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

784
Views
¿Cómo verificar si existe la tabla DynamoDB?

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Al leer la documentación, puedo ver que hay tres métodos mediante los cuales puede verificar si existe una tabla.

  1. La API CreateTable arroja un error ResourceInUseException si la tabla ya existe. Envuelva el método create_table con try excepto para capturar esto
  2. Puede usar la API ListTables para obtener la lista de nombres de tablas asociados con la cuenta actual y el punto final. Compruebe si el nombre de la tabla está presente en la lista de nombres de tablas que obtiene en la respuesta.
  3. La API DescribeTable generará un error ResourceNotFoundException 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 pass

Ejemplo 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 pass
over 4 years ago · Santiago Trujillo Report

0

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)
over 4 years ago · Santiago Trujillo Report

0

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')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!