簡體   English   中英

當 DynamoDB 中不存在項目時,如何使用 Python (boto3) 強制 delete_item 返回錯誤?

[英]How to force delete_item using Python (boto3) to return an error when an item does not exist in DynamoDB?

默認情況下,來自 boto3 的 delete_item 不會返回錯誤,即使對不存在的 Item 執行操作也是如此。

id = '123'
timenow = '1589046426'

dynamodb = boto3.resource('dynamodb')
boto3_table = dynamodb.Table(MY_TABLE)
response = boto3_table.delete_item(Key={"ID": id, "TIMENOW": timenow})

當 item 不存在時,如何更改上面的代碼以強制 delete_item 返回錯誤?

一種方法是使用分區鍵屬性名稱上的條件表達式進行條件刪除

response = table.delete_item(
    Key={
        'pk': "jim.bob",
        "sk": "metadata"
    },
    ConditionExpression="attribute_exists (pk)",
)

如果該項目與該鍵存在並且作為分區鍵的屬性存在於該鍵上,它將刪除該項目。 如果該項目不存在,那么您將獲得:

The conditional request failed

如果有人有同樣的問題,這里是解決方案:

response = boto3_table.delete_item(Key={"IDID": idid, "TIMENOW": timenow},
           ConditionExpression="attribute_exists(ID) AND attribute_exists(TIMENOW)")

僅當 ID 和 TIMENOW 出現在記錄中時,帶有 attribute_exists 的 ConditionExpression 參數才會刪除。

另一種方法是使用ReturnValues='ALL_OLD'返回與給定鍵關聯的屬性(如果它們在之前已被刪除):

response = boto3_table.delete_item(Key={"ID": id, "TIMENOW": timenow}, ReturnValues='ALL_OLD')
if not res['Attributes']:
  raise KeyError('Item not found!')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM