Lambda函数调用数据库

时间:2019-02-23 08:12:28

标签: python-3.x aws-lambda amazon-dynamodb

我是AWS / Lambda / Amazon Connect的新手,正在尝试解决这个问题。我有以下代码从dynamoDB表中请求信息,并在有新条目的情况下更新该表。我的问题是该函数似乎只运行except部分,而完全忽略了try。需要了解为什么

代码

import boto3
import json
from boto3.dynamodb.conditions import Key, Attr

def lambda_handler(event, context):
    print("Lambda Trigger event: " + json.dumps(event))

    try:

        phoneNumber = event['Details']['ContactData']['CustomerEndpoint']['Address']
        print("Customer Phone Number : " + phoneNumber)

        dynamodb = boto3.resource('dynamodb',region_name='ap-southeast-2')

        table = dynamodb.Table('data_dip_table')

        response = table.get_item(Key={
                                'phone-number': phoneNumber
                                })
        print("dynamodb response: " + json.dumps(response))

        if 'Item' in response:
            # TODO: Match Found
            print("Phone number match found!")

            firstName = response['Item']['first-name']
            print("Customer First Name: " + firstName)

            welcomeMessage = 'Welcome' + firstName + ' to Our data dip'
            print("welcome message :" + welcomeMessage)

            return {'welcomeMessage' : welcomeMessage }

        else:
            print("Phone Number was not Found")

            return { 'welcomeMessage' : 'Welcome!' }

    except Exception as e:
        print("An Error Has Occurred")
        print(e)
        return {'welcomeMessage' : 'Welcome !'}

我的输出是

响应: {   “ welcomeMessage”:“欢迎!” }

请求ID: “ 0d9b6bf6-62f8-4385-81f0-f1d36ee489c8”

功能日志: START RequestId:0d9b6bf6-62f8-4385-81f0-f1d36ee489c8版本:$ LATEST Lambda触发事件:{} 发生了错误 '细节' END RequestId:0d9b6bf6-62f8-4385-81f0-f1d36ee489c8

我在DD表中输入了我的电话号码,但仍然收到错误提示。

1 个答案:

答案 0 :(得分:0)

event对象为空。在CloudWatchLogs中检查以下行:

Lambda Trigger event: {}

您的代码绝对不会忽略try块,但是,在try块的第一行,您会phoneNumber = event['Details']['ContactData']['CustomerEndpoint']['Address']自动失败,因为您的事件为空,因此将执行重定向到except块。

该功能如何触发?如果您是通过AWS控制台手动进行的,则必须创建一个包含事件,该事件包含您的方法期望的主体。