【问题标题】:python: clean dynamoDB AWS item?python:清理 dynamoDB AWS 项目?
【发布时间】:2023-01-20 20:02:27
【问题描述】:

通过 AWS DynamoDB 调用,我们有时会得到复杂的项目,它精确地确定了项目中每个元素的类型。 它可能很有用,但提取数据很麻烦。

{
 "a": {
  "S": "AAAA"
 },
 "myList": {
  "L": [
   {
    "S": "T1"
   },
   {
    "S": "T2"
   },
   {
    "S": "TH"
   }
  ]
 },
 "checkList": {
  "L": [
   {
    "M": {
     "id": {
      "S": "telesurveyor"
     },
     "check": {
      "BOOL": true
     }
    }
   }
  ]
 },
 "createdAt": {
  "N": "1672842152365"
 },
}

我们需要将其转换为:

{
 "a": "AAAA",
 "myList": ["T1","T2","TH"],
 "checkList": [
   {
     "id": "telesurveyor",
     "check": true
   }
  ],
 "createdAt": 1672842152365,
}

有 AWS boto3 方法吗? 如果是,那是什么?如果没有,如何手动完成?

【问题讨论】:

标签: python amazon-web-services dictionary amazon-dynamodb


【解决方案1】:

使用高级Table接口而不是低级Client接口。以前的自动封送本地 DynamoDB 属性(例如"count" : { "N": "23" })和本地 Python(例如"count": 23)之间的值

例如:

import boto3

TABLE = "my-data"

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(TABLE)

item = table.get_item(Key={"pk": "1", "sk": "2"})

if 'Item' in item:
    print(item["Item"])

【讨论】:

    【解决方案2】:

    您可以通过两种方式实现这一目标:

    1. Resource Table Client

    这是一个更高级别的客户端,它抽象了 DynamoDB JSON 并允许您使用本机 JSON 对象来写入和读取 DynamoDB。

    客户端实例化与之前类似,只是声明 Table 资源并为其提供表名。

    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('name')
    

    2. TypeSerializer

    如果您已经使用了低级客户端但想要为特定目的解组数据,则第二个选项很有用。它使用 boto3 TypeSerializer:

    import boto3
    boto3.resource('dynamodb')
    deserializer = boto3.dynamodb.types.TypeDeserializer()
    
    item = {
        "a": {
            "S": "AAAA"
        },
        "myList": {
            "L": [
                {
                    "S": "T1"
                },
                {
                    "S": "T2"
                },
                {
                    "S": "TH"
                }
            ]
        },
        "checkList": {
            "L": [
                {
                    "M": {
                        "id": {
                            "S": "telesurveyor"
                        },
                        "check": {
                            "BOOL": "True"
                        }
                    }
                }
            ]
        },
        "createdAt": {
            "N": "1672842152365"
        },
    }
    
    data = {k: deserializer.deserialize(v) for k, v in item.items()}
    print(data)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2016-12-07
      • 2017-07-08
      • 2019-05-25
      • 2016-05-04
      • 2012-05-26
      • 2019-08-16
      相关资源
      最近更新 更多