Python lambda 函数返回 KeyError

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

我正在尝试使用 Python 3.6 创建简单的 Lambda 函数。

该函数应该在请求查询字符串参数中获取一个 userId(我在 DynamoDB 中的主键),如果项目存在于数据库中则返回 200,这是我的 lambda 函数

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

def lambda_handler(event, context):

  userId = event["userId"]

  dynamodb = boto3.resource('dynamodb')
  table = dynamodb.Table(os.environ['Customers'])
  items = table.query(
  KeyConditionExpression=Key('userId').eq(userId)
  )

  return items["Items"]

当我在 Lambda 接口(interface)中进行测试时,它可以工作并返回正确的用户,但是,当从 Postman 尝试或使用 API 网关时,它返回以下错误

{
"errorMessage": "'userId'",
"errorType": "KeyError",
"stackTrace": [
    [
        "/var/task/index.py",
        7,
        "lambda_handler",
        "userId = event["userId"]"
    ]
]
}
  • 我在这里缺少什么?
  • 努力理解“事件”,文档说明它是一个 python 字典,但我如何打印它的结果并实际调试 lambda 当从 Postman 或 API Gateway 调用时?

最佳答案

您正在使用 event["userId"],这意味着例如发送请求负载

GET API : api/users/
Request Body payload:

{
"userId":"1234"
}

然后上面的代码就可以工作了,假设你想发送 userId 作为路径参数

GET API :api/user/{userId}

然后你可以在lambda函数中访问

userId = (event['pathparameters']['userId'])

最好加上打印语句 打印(事件)并查看cloudwatch日志中的日志

关于Python lambda 函数返回 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535861/

相关文章:

python - imageio-值错误: Could not find a format to read the specified file in mode 'i'

linux - 如何在运行 Amazon Linux Distro 的 EC2 t2.micro 实例上安装 PHP 7

node.js - 如何在 AWS 中的 NodeJS 中编写 Mongo 副本脚本

python - 我得到 : "object does not support item assignment" when populating a dictionary

python - 如何从字典创建两列数据框

python - 单对象迭代器

amazon-web-services - EC2 IAM 策略需要标签

python - 在 django 中使用 FFMPEG 在网络上上传后从视频中提取 WAV 音频文件

python-3.x - cython 编译 - 导入与 cimport

python - 敌人不会显示