【问题标题】:How to handle null attributes while fetching data from dynamodb从 dynamodb 获取数据时如何处理空属性
【发布时间】:2022-02-08 04:16:30
【问题描述】:

我有一个简单的表,其中主键是 ID,其他属性是名称和余额。现在有些行 balance 可以为 NULL。当我使用 Lambda 函数获取这些属性时,它无法处理。我想处理这些情况,以便在检测到 NULL 属性时可以显示一些消息。

import json
import boto3
def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("demoTable")
    response = table.get_item(
    Key = {
            'ID': '9898'
    }
    
    )
    item = str(response['Item']['balance'])
    print(item)

【问题讨论】:

    标签: amazon-web-services aws-lambda amazon-lex aws-lambda-layers amazon-dynamodb


    【解决方案1】:

    你的问题出在:

    response['Item']['balance']

    通常,使用方括号访问字典成员(响应是字典)被认为是一种不好的做法。当您完全确定要获取的项目存在时,您可以使用它,但更好的方法是使用get(),因为它可以处理项目不存在的情况。

    response.get('Item', dictionary()).get('balance', 0)
    

    如果该项目不存在,或者余额为空,则结果为 0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 2014-01-09
      • 1970-01-01
      相关资源
      最近更新 更多