【问题标题】:How do I add a list of dict to DynamoDB using the put_item method in boto3如何使用 boto3 中的 put_item 方法将 dict 列表添加到 DynamoDB
【发布时间】:2021-06-23 17:45:52
【问题描述】:

我在使用 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,但我不知道如何格式化购物车。

【问题讨论】:

  • 你给的例子列表是cart的例子吗?你遇到了什么错误?

标签: python aws-lambda amazon-dynamodb boto3


【解决方案1】:

需要注意的几点:

  • 我们不需要指定类型,dynamo客户端会根据python变量类型来假设类型
  • 浮点数是不可接受的(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

        }
)

【讨论】:

  • parse_float 未定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 2016-08-23
  • 2021-08-11
  • 2021-07-18
  • 1970-01-01
相关资源
最近更新 更多