Andre
Andre

Reputation: 694

Querying a DynamoDB with Python

When querying a DynamoDB table, the code works fine for a valid entry (msisdn) however, for non-existent entries it does crash.

import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('PhoneList')

# Phone Number 
# -> Existent: 44790000000
msisdn = 44790000000

try:
    response = table.get_item(Key={'MSISDN': msisdn})
    
    name = response['Item']['Name']
    ID = str(response['Item']['ID'])
    birth = response['Item']['Birth']
    
except ClientError as e:
    print(e.response['Error']['Message'])
    print("Phone number not found")
    exit(-1)

print("Phone:", msisdn)
print("Name:", name)
print("ID:", id)
print("Birth:", birth)

Invalid Entry

Traceback (most recent call last):
  File "dyn.py", line 15, in <module>
    name = response['Item']['Name']
KeyError: 'Item'

Database

enter image description here

I think I might not handled correctly the Exception?

Upvotes: 0

Views: 592

Answers (1)

Cyril Jouve
Cyril Jouve

Reputation: 1040

from the documentation

If there is no matching item, GetItem does not return any data and there will be no Item element in the response.

so you need to catch KeyError instead of ClientError.

Upvotes: 1

Related Questions