Python 3.x 测试AWS Lambda处理程序函数时出错:事件和上下文参数的数据格式

Python 3.x 测试AWS Lambda处理程序函数时出错:事件和上下文参数的数据格式,python-3.x,amazon-web-services,aws-lambda,aws-lex,Python 3.x,Amazon Web Services,Aws Lambda,Aws Lex,我从一个博客中得到了以下代码,它得到了今天比特币的价格。我可以从AWS Lex控制台访问这个Lambda函数,并测试bot以获得今天的价格 """ Lexbot Lambda handler. """ from urllib.request import Request, urlopen import json def get_bitcoin_price(date): print('get_bitcoin_price, date = ' + str(date)) request

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

"""
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函数的“事件”和“上下文”的格式是什么?还有,这里的“上下文”是什么


在本例中,我应该将什么作为“事件”和“上下文”传递?

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

date\u input=event['currentIntent']['slots']['date']

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

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

现在,在下拉列表中,您可以选择您的事件,AWS将为您填写,如下所示:

{
  "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)"
  }
}

现在,您可以根据自己的需要定制活动

保存它并单击Test后,将使用提供的JSON填充
事件
对象

另一个选项是检查,这样您就可以简单地获取您想要的任何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)"
  }
}
将其用作您的事件,您将能够相应地对其进行测试