Python lambda函数返回KeyError

问题描述 投票:3回答:1

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

该函数应该在请求查询字符串params中获取userId(我在DynamoDB中的主键),如果DB中存在item,则返回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接口中进行测试时,它可以工作并返回正确的用户,但是当从Postman尝试或使用API​​网关时,它会返回以下错误

{
"errorMessage": "'userId'",
"errorType": "KeyError",
"stackTrace": [
    [
        "/var/task/index.py",
        7,
        "lambda_handler",
        "userId = event["userId"]"
    ]
]
}
  • 我在这里失踪了什么?
  • 为了理解“事件”而苦苦挣扎,文档声明它是一个python字典,但是如何打印它的结果并在从Postman或API Gateway调用时实际调试lambda?
python python-3.x amazon-web-services aws-lambda
1个回答
2
投票

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

GET API : api/users/
Request Body payload:

{
"userId":"1234"
}

然后上面的代码工作,假设您要发送userId作为路径参数

GET API :api/user/{userId}

然后你可以访问lambda函数

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

更好地添加print语句print(事件)并检查cloudwatch日志中的日志

© www.soinside.com 2019 - 2024. All rights reserved.