测试 AWS Lambda 处理函数时出错:事件和上下文参数的数据格式

Error on testing AWS Lambda handler function: Data format for event and context parameters

我从博客中获得了以下代码,它获取了今天的比特币价格。我可以从 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'是什么格式?另外,这里的 'context' 是什么?

在我的情况下,我应该传递什么作为 'event' 和 'context'?

您的代码失败是因为 event 对象填充了 {'Date': 'Feb 22'},但您的代码期望的远不止于此。因此,当您尝试通过访问 currentIntent:

来解析此 JSON 时,它会失败

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

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

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

现在,在下拉列表中,您可以 select 您的事件,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)"
  }
}

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