Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name 'Key' not defined Lambda function to access DynamoDB

I am using the query function from the boto3 library in Python and receiving the following error:

name 'Key' is not defined: NameError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 51, in lambda_handler
if not getAssetExistance(slack_userID):
File "/var/task/lambda_function.py", line 23, in getAssetExistance
response = dynamoTable.query(KeyConditionExpression=Key('userID').eq(asset))
NameError: name 'Key' is not defined

I have been reading through a bunch of tutorials on accessing DynamoDB through Lambda, and this they all use this KeyConditionExpression line when trying to if a key exists.

Here is the relevant code (line 23 is the query line):

def getAssetExistance(asset):
    dynamoTable = dynamo.Table('Assets')
    response    = dynamoTable.query(KeyConditionExpression=Key('userID').eq(asset))

    return bool(response)

I basically want to check the primary partition key in my DynamoDB table (which is a slack user ID) and see if exist.

Here is the rest of the code if it is relevant:

################################
# Slack Lambda handler.
################################

import boto3
import logging
import os
import urllib

# Grab data from the environment.
BOT_TOKEN   = os.environ["BOT_TOKEN"]
ASSET_TABLE = os.environ["ASSET_TABLE"]
REGION_NAME = os.getenv('REGION_NAME', 'us-east-1')

dynamo = boto3.resource('dynamodb', region_name=REGION_NAME, endpoint_url="https://dynamodb.us-east-1.amazonaws.com")

# Define the URL of the targeted Slack API resource.
SLACK_URL = "https://slack.com/api/chat.postMessage"

def getAssetExistance(asset):
    dynamoTable = dynamo.Table('Assets')
    response    = dynamoTable.query(KeyConditionExpression=Key('userID').eq(asset))

    return bool(response)

def lambda_handler(data, context):
    # Slack challenge answer.
    if "challenge" in data:
        return data["challenge"]

    # Grab the Slack channel data.
    slack_event    = data['event']
    slack_userID   = slack_event["user"]
    slack_text     = slack_event["text"]
    channel_id     = slack_event["channel"]
    slack_reply    = ""

    # Ignore bot messages.
    if "bot_id" in slack_event:
        slack_reply = ""
    else:

        # Start data sift.
        if slack_text.startswith("!networth"):
            slack_reply = "Your networth is: "
        elif slack_text.startswith("!price"):
            command,asset = text.split()
            slack_reply = "The price of a(n) %s is: " % (asset)
        elif slack_text.startswith("!addme"):
            if not getAssetExistance(slack_userID):
                slack_reply = "Adding user: %s" % (slack_userID)
                dynamo.update_item(TableName=ASSET_TABLE, 
                    Key={'userID':{'S':'slack_userID'}},
                    AttributeUpdates= {
                        'resources':{
                            'Action': 'ADD',
                            'Value': {'N': '1000'}
                        }
                    }
                )
            else:
                slack_reply = "User %s already exists" % (slack_userID)

        # We need to send back three pieces of information:
        data = urllib.parse.urlencode(
            (
                ("token", BOT_TOKEN),
                ("channel", channel_id),
                ("text", slack_reply)
            )
        )
        data = data.encode("ascii")

        # Construct the HTTP request that will be sent to the Slack API.
        request = urllib.request.Request(
            SLACK_URL, 
            data=data, 
            method="POST"
        )
        # Add a header mentioning that the text is URL-encoded.
        request.add_header(
            "Content-Type", 
            "application/x-www-form-urlencoded"
        )

        # Fire off the request!
        urllib.request.urlopen(request).read()

    # Everything went fine.
    return "200 OK"

My DynamoDB table is named 'Assets' and has a primary partition key named 'userID' (string).

I am definitely still new to all this, so don't be afraid of calling me a dummy. Any and all help is appreciated. The goal of this code is to check if a user exists as a key in DynamoDB and if not, add them to the table.

like image 603
slnd54 Avatar asked Mar 21 '18 13:03

slnd54


2 Answers

You need to import the Key function, like so:

from boto3.dynamodb.conditions import Key
like image 170
Mark B Avatar answered Oct 26 '22 03:10

Mark B


Without importing it second time, u can address it like: boto3.dynamodb.conditions.Key

def getAssetExistance(asset):
dynamoTable = dynamo.Table('Assets')
response    = dynamoTable.query(KeyConditionExpression= boto3.dynamodb.conditions.Key('userID').eq(asset))

return bool(response)
like image 42
Saigets Avatar answered Oct 26 '22 04:10

Saigets