简体   繁体   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?

By default delete_item from boto3 does not return an error even if operation is performed on an Item that does not exists.默认情况下,来自 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})

How do I change the code above to force the delete_item to return an error when item does not exist?当 item 不存在时,如何更改上面的代码以强制 delete_item 返回错误?

One way would be to do a conditional delete using a condition-expression on the your partition key attribute name:一种方法是使用分区键属性名称上的条件表达式进行条件删除

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

If the item exists with this key AND the attribute that is the partition key exists on that key, it deletes the item.如果该项目与该键存在并且作为分区键的属性存在于该键上,它将删除该项目。 If the item does not exist, then you get:如果该项目不存在,那么您将获得:

The conditional request failed

If anyone has the same problem, here is the solution:如果有人有同样的问题,这里是解决方案:

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

The ConditionExpression parameter with attribute_exists will only delete if the ID and TIMENOW are present in the record.仅当 ID 和 TIMENOW 出现在记录中时,带有 attribute_exists 的 ConditionExpression 参数才会删除。

Another approach would be to use ReturnValues='ALL_OLD' which returns attributes associated with a given key if they existed prior removal:另一种方法是使用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