【问题标题】:Reading Data from Dynamodb using Alexa with lambda function使用 Alexa 和 lambda 函数从 Dynamodb 读取数据
【发布时间】:2020-05-23 04:26:47
【问题描述】:

我正在尝试使用 alexa 从我的 dynamo db 表中读取数据,但我的 lambda 函数似乎无法访问我的表。 这是从 dynamodb 获取数据的代码:

# Gets the data from dynamodb based on userid

def GetData(session):
    userId = session['user']['userId'].split('.')
    userId = userId[3]
    try:
        response = table.query(
            KeyConditionExpression=Key('guid').eq(str(userId))
        )

        # print ("Got data: " + str(len(response)))
        print(response)
        for item in response['Items']:
            final_response = item["command"]
            tstamp = item["tstamp"]

        if (response['Count'] == 0):
            final_response = "No Data with this userid. You can ask to get the userid"

        else:
            now = datetime.datetime.utcnow()
            timestamp = int(round((now - datetime.datetime(2016, 1, 1)).total_seconds()))
            if ((timestamp - int(tstamp)) > 60):
                final_response = "No Data received from device in past 1 minute"

        return final_response
    except ClientError as e:
        print(e.response['Error']['Message'])

当我向 Alexa 询问我的自定义问题时,我得到的唯一回答是没有此用户 ID 的数据。您可以要求获取用户 ID。 当我测试运行我的 lambda 函数时,它运行成功。但它没有查询数据库。

【问题讨论】:

  • 我不是 python 人,但错误似乎表明您在 event 对象上请求密钥“会话”,并且它不存在。
  • 我设法消除了错误。但是 lambda 函数仍然没有从 Dynamo db 中读取数据。当我触发 alexa 时,她只是说:“此用户 ID 没有数据。您可以要求获取用户 ID”。

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


【解决方案1】:

如果要根据userId进行存储和检索,可以使用ASK SDK中提供的persistenceAdapter接口。看起来你目前没有使用它。我肯定会推荐它,因为它可以更轻松地管理不同 Intent 的处理程序(并提供像这样的有用抽象)。询问 SDK 文档https://developer.amazon.com/en-US/docs/alexa/alexa-skills-kit-sdk-for-python/overview.html

抽象将允许您使用 S3 或 Dynamo 作为实现者。这是 dynamoDB 库。 https://github.com/alexa/alexa-skills-kit-sdk-for-python/tree/master/ask-sdk-dynamodb-persistence-adapter

使用 SkillBuilder 构造函数(例如)创建和注册 Dynamo 适配器:https://github.com/alexa/skill-sample-python-highlowgame/blob/master/lambda/py/lambda_function.py#L16

使用您的适配器(例如):https://github.com/alexa/skill-sample-python-highlowgame/blob/master/lambda/py/lambda_function.py#L130

在使用适配器时,请记住,直到您保存后才会发生发电机写入调用,因此您可以随意修改对象,直到您调用保存为止。所有 handler_input 对象都通过 attributes_manager 引用了 persistent_attributes(这也让您可以轻松使用 session_attributes)

【讨论】:

  • 非常感谢您向我介绍这一点。能否请您举一个使用 ask-sdk 连接 alexa 和 dynamodb 的示例。
  • 查看上面指向 python highlow 游戏示例的链接。这是项目的根目录:github.com/alexa/skill-sample-python-highlowgame
猜你喜欢
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2021-09-20
  • 2019-07-28
相关资源
最近更新 更多