Dynamodb put_item()覆盖d

2024-06-14 08:10:20 发布

您现在位置:Python中文网/ 问答频道 /正文

Device是我的分区键,table用于在同一个设备下放置多个不同的用户。但是,如果我运行下面的put_item()代码,它将覆盖每个拥有相同设备密钥的用户。在

示例:如果我放入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, 

Tags: the用户importjsonreturnputdevicetable
2条回答

来自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 指定分区键尚不存在。在

下面这样的方法应该可以工作(抱歉,我没有完全了解您的密钥方案,因此您必须修改此方案)。在

table.put_item(
    Item={'userId': 1, 'productId': 2}, 
    ConditionExpression='userId <> :uid AND productId <> :pid', 
    ExpressionAttributeValues={':uid': 1, ':pid': 3}
)

你在找^{}。您应该使用UpdateExpression,因为AttributeUpdates已被弃用,但是这个简单的示例应该可以让您开始:

response = table.update_item(
   Key={
     'Device': device,
   },
   AttributeUpdates={
     'RequestList': {
       'Alias': aliasInput,
       'Date': date
     },
     'AvailableQuanity': 0,
     'ReserveQuanity': 0,
   },
)

相关问题 更多 >