[英]boto dynamodb batch_write and delete_item — 'The provided key element does not match the schema'
[英]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 = 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.