我对 AWS Serverless 非常陌生,并选择使用 Python 作为我的 Lambda 处理程序
当我使用 API Gateway 查询 DynamoDB 以获取表中的项目时,如果该项目不存在,则会抛出此错误。如果该项目不存在,我只是想让它不返回任何内容。这是错误:
{
"errorMessage": "'Item'",
"errorType": "KeyError",
"stackTrace": [" File \"/var/task/lambda_function.py\", line 11, in lambda_handler\n json_body = response['Item']\n"]
}
我进行了高低搜索,尝试在 DynamoDB 响应中查找属性,这些属性会告诉我没有项目,然后我可以基于此编写一个 If 语句。
这是我的 Lambda 代码:
import json
import boto3
def lambda_handler(event, context):
client = boto3.resource("dynamodb")
table = client.Table("pnr-snapshot")
pnrID = event['pnrID']
response = table.get_item(Key={'pnrID': pnrID})
json_body = response['Item']
return json_body
我想也许在代码中添加一个尝试会有所帮助,但我却得到了这个语法错误:
{"errorMessage":"Syntax error in module 'lambda_function': unexpected EOF while parsing (lambda_function.py, line 12)","errorType":"Runtime.UserCodeSyntaxError","stackTrace":[" File "/var/task/lambda_function.py" Line 12\n \t\treturn json_body\n"]}
import json
import boto3
def lambda_handler(event, context):
client = boto3.resource("dynamodb")
table = client.Table("pnr-snapshot")
pnrID = event['pnrID']
try:
response = table.get_item(Key={'pnrID': pnrID})
json_body = response['Item']
return json_body
我真的很感激任何帮助......
最佳答案
无法执行以下检查 key 是否存在?
import json
import boto3
def lambda_handler(event, context):
client = boto3.resource("dynamodb")
table = client.Table("pnr-snapshot")
pnrID = event['pnrID']
response = table.get_item(Key={'pnrID': pnrID})
if 'Item' in response:
json_body = response['Item']
return json_body
else:
return ''
关于python - Lambda Python : How to check if get_item returned a value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62729284/