如何使用 boto3 中的 put_item 方法将字典列表添加到 DynamoDB

How do I add a list of dict to DynamoDB using the put_item method in boto3

我在使用 client.put_item 方法将字典列表放入我的 table 时遇到问题。字典的格式为:{"name": "beef", "price":5.23}。此类列表的一个示例是:[{"name": "chicken", "price":6.23}, {"name": "beef", "price":5.34}, {"name": "pork", "price":8.48}] 其中 列表大小可能会有所不同 。到目前为止我有

def create_order(order_id, cart, total):
    dynamodb = boto3.client('dynamodb')
    table = 'Orders'
    response = dynamodb.put_item(TableName=table,
       Item={
            'order_id': {"S":order_id},
            'order_total': {"N":str(total)},
            'cart':{"L":cart}
            
        }
    )
    return response

它适用于 order_id 和 order_total,但我不知道如何格式化购物车。

有两点需要注意:

  • 我们不需要指定类型,dynamo 客户端将根据 python 变量类型
  • 假定类型
  • 浮点数是不可接受的(open issue),因此,最简单的方法是转换为 json 并返回对象 parse_float=Decimal

这是一个例子:

import json
import boto3
from decimal import Decimal
dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
table = dynamodb.Table('Orders')
order_id = "1000"
total = 100
cartBefore = [{"name": "chicken", "price":6.23}, {"name": "beef", "price":5.34}, {"name": "pork", "price":8.48}]
cart = json.loads(json.dumps(cartBefore), parse_float=Decimal)
response = table.put_item(
        Item={
                'id': '10',  
                'order_id': order_id,
                'order_total': total,
                'cart': cart

        }
)