Search code examples
pythonamazon-dynamodbboto3

How to get the if statement right for boto3


I created a dynamodb table with two records in there. One is the ARN of the rds and one is date field name last_reported. Now i am trying to run lambda function which should fetch that record. If there is data in the table it should execute the value of the table / item, if there is no data in the table, it should exit with a message. I get the following error

  {
    "errorMessage": "'Item'",
    "errorType": "KeyError",
    "requestId": "",
    "stackTrace": [
    "  File \"/var/lang/lib/python3.9/importlib/__init__.py\", line 127, in import_module\n    
    return _bootstrap._gcd_import(name[level:], package, level)\n",
   "  File \"<frozen importlib._bootstrap>\", line 1030, in _gcd_import\n",
"  File \"<frozen importlib._bootstrap>\", line 1007, in _find_and_load\n",
"  File \"<frozen importlib._bootstrap>\", line 986, in _find_and_load_unlocked\n",
"  File \"<frozen importlib._bootstrap>\", line 680, in _load_unlocked\n",
"  File \"<frozen importlib._bootstrap_external>\", line 850, in exec_module\n",
"  File \"<frozen importlib._bootstrap>\", line 228, in _call_with_frames_removed\n",
"  File \"/var/task/lambda_function.py\", line 339, in <module>\n    lambda_handler(1,1)\n",
"  File \"/var/task/lambda_function.py\", line 263, in lambda_handler\n    last_reported = int(read_db['Item']['last_reported']['N'])\n"

] }

  dynamo_table_name = 'my_table'
  key = 'arn'
  dynamo = boto3.client('dynamodb', region_name=source_region,  config=Config(connect_timeout=5, read_timeout=60, retries={'max_attempts': 10}))
          response = dynamo.query(
            TableName=dynamo_table_name, 
            KeyConditionExpression="arn = :arn",
            ExpressionAttributeValues={":arn": {"S":arn}}
            )
          if response == True
            read_db = dynamo.get_item(TableName=dynamo_table_name, Key={'arn':{'S':arn}})
            last_reported = int(read_db['Item']['last_reported']['N'])
            print (last_reported)

Solution

  • You need to be sure your get_item returned an item, you can do that by checking for the existence of the Item key in the dict returned:

    read_db = dynamo.get_item(TableName=dynamo_table_name, Key={'arn':{'S':arn}})
    
    if 'Item' in read_db:
        # your logic