【问题标题】:Error on testing AWS Lambda handler function: Data format for event and context parameters测试 AWS Lambda 处理程序函数时出错:事件和上下文参数的数据格式
【发布时间】:2019-07-19 11:03:00
【问题描述】:

我从博客中获得了以下代码,该代码获取了今天的比特币价格。我可以从 AWS Lex 控制台访问这个 Lambda 函数并测试机器人以获得今天的价格。

"""
Lexbot Lambda handler.
"""
from urllib.request import Request, urlopen
import json

def get_bitcoin_price(date):
    print('get_bitcoin_price, date = ' + str(date))
    request = Request('https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/latest?period_id=1DAY&limit=1&time_start={}'.format(date))
    request.add_header('X-CoinAPI-Key', 'E4107FA4-A508-448A-XXX')
    response = json.loads(urlopen(request).read())
    return response[0]['price_close']

def lambda_handler(event, context):
    print('received request: ' + str(event))
    date_input = event['currentIntent']['slots']['Date']
    btc_price = get_bitcoin_price(date_input)
    response = {
        "dialogAction": {
            "type": "Close",
            "fulfillmentState": "Fulfilled",
            "message": {
              "contentType": "SSML",
              "content": "Bitcoin's price was {price} dollars".format(price=btc_price)
            },
        }
    }
    print('result = ' + str(response))
    return response

但是当我从 AWS Lex 控制台测试函数时,我收到以下错误:

 Response:
{
  "errorMessage": "'currentIntent'",
  "errorType": "KeyError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      18,
      "lambda_handler",
      "date_input = event['currentIntent']['slots']['Date']"
    ]
  ]
}

Request ID:
"2488187a-2b76-47ba-b884-b8aae7e7a25d"

Function Logs:
START RequestId: 2488187a-2b76-47ba-b884-b8aae7e7a25d Version: $LATEST
received request: {'Date': 'Feb 22'}
'currentIntent': KeyError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 18, in lambda_handler
    date_input = event['currentIntent']['slots']['Date']
KeyError: 'currentIntent'

如何在 AWS Lambda 控制台中测试函数? 'lambda_handler' 函数,'event' 和 'context' 的格式是什么?另外,这里的“背景”是什么?

在我的情况下,我应该传递什么作为“事件”和“上下文”?

【问题讨论】:

    标签: python-3.x amazon-web-services aws-lambda aws-lex


    【解决方案1】:

    您的代码失败了,因为event 对象被{'Date': 'Feb 22'} 填充,但您的代码期望的远不止这些。因此,当您尝试通过访问currentIntent 来解析此 JSON 时,它会失败:

    date_input = event['currentIntent']['slots']['Date']

    从控制台进行测试时,您不能将任何 context 传递给您的 Lambda,因为它是由 AWS 自动填充的。另外,上下文只在非常特定的场合使用,所以我暂时不用担心。

    但是,您可以将event 作为参数传递,并且有很多方法可以做到这一点。手动操作最简单的方法是进入 AWS 的 Lambda 控制台,点击测试,如果您还没有配置任何测试事件,则会弹出以下屏幕

    现在,在下拉列表中,您可以选择您的活动,AWS 会为您填写,如下所示:

    您现在可以按照自己的方式自定义活动。

    保存并单击测试后,event 对象将使用提供的 JSON 填充。

    另一种选择是检查Sample Events Published By Event Sources,这样您就可以简单地抓取任何您想要的 JSON 事件并相应地对其进行调整。

    我已经为您获取了 Lex 示例事件,如下所示:

    {
      "messageVersion": "1.0",
      "invocationSource": "FulfillmentCodeHook or DialogCodeHook",
      "userId": "user-id specified in the POST request to Amazon Lex.",
      "sessionAttributes": { 
         "key1": "value1",
         "key2": "value2",
      },
      "bot": {
        "name": "bot-name",
        "alias": "bot-alias",
        "version": "bot-version"
      },
      "outputDialogMode": "Text or Voice, based on ContentType request header in runtime API request",
      "currentIntent": {
        "name": "intent-name",
        "slots": {
          "slot-name": "value",
          "slot-name": "value",
          "slot-name": "value"
        },
        "confirmationStatus": "None, Confirmed, or Denied
          (intent confirmation, if configured)"
      }
    }
    

    将其用作您的事件,您将能够相应地对其进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 2020-02-25
      • 2016-09-04
      相关资源
      最近更新 更多