gpt4 book ai didi

python - 如何使用 boto3 中的 put_item 方法将 dict 列表添加到 DynamoDB

转载 作者:行者123 更新时间:2023-12-04 07:53:29 25 4
gpt4 key购买 nike

我在使用 client.put_item 方法将字典列表放入我的表时遇到问题。字典的格式为:{"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 变量类型
  • 假设类型
  • float 是 Not Acceptable ( open issue ),因此,使用 parse_float=Decimal 转换为 json 并返回到对象的最简单方法.

  • 下面是一个例子:
    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

    }
    )

    关于python - 如何使用 boto3 中的 put_item 方法将 dict 列表添加到 DynamoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66824695/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com