gpt4 book ai didi

python - Dynamodb put_item() 覆盖数据

转载 作者:行者123 更新时间:2023-12-04 03:02:34 25 4
gpt4 key购买 nike

设备是我的分区键,表用于放置多个不同的用户,在同一个设备下。但是,如果我运行以下 put_item() 代码,如果每个用户具有相同的设备 key ,它将覆盖每个用户。

示例:如果我输入 Monitor , 作为我的 device变量,和 gomez作为我的 aliasInput它运行的变量。
然后再次以 Monitor 运行它再次作为我的 device可变,但 craig作为我的 aliasInput它覆盖了我的 gomez入口。

将数据输入到我的表中的函数:

import boto3
import json
import decimal
import time
import datetime

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)


dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

table = dynamodb.Table('WishListTest')

device = input('What is the Item being requested?\n')
device = device.upper()

aliasInput = input('What is the Alias of the user?\n')
aliasInput = aliasInput.upper()

date = int((time.strftime("%d%m%Y")))
response = table.put_item(
Item={
'Device': device,
'RequestList': {
'Alias': aliasInput,
'Date': date
},
'AvailableQuanity': 0,
'ReserveQuanity': 0,

}
)

print("PutItem succeeded:")
print(json.dumps(response,

最佳答案

来自 the docs:
放置项目

Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item.



为防止覆盖,您需要添加 conditional expression
指定分区键尚不存在。

像下面这样的东西应该可以工作(抱歉,我不太明白你的 key 方案,所以你必须修改它)。
table.put_item(
Item={'userId': 1, 'productId': 2},
ConditionExpression='userId <> :uid AND productId <> :pid',
ExpressionAttributeValues={':uid': 1, ':pid': 3}
)

关于python - Dynamodb put_item() 覆盖数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47859052/

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