当 DynamoDB 中不存在某个项目时,如何使用 Python (boto3) 强制 delete_item 返回错误?

Leo*_*Leo 3 python python-3.x amazon-dynamodb boto3

默认情况下,即使对不存在的项目执行操作,boto3 中的delete_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})
Run Code Online (Sandbox Code Playgroud)

如何更改上面的代码以强制 delete_item 在项目不存在时返回错误?

Kir*_*irk 6

一种方法是使用分区键属性名称上的条件表达式进行条件删除:

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

如果该项与此键一起存在,并且作为分区键的属性存在于该键上,则会删除该项。如果该项目不存在,那么您将得到:

The conditional request failed
Run Code Online (Sandbox Code Playgroud)


Leo*_*Leo 5

如果有人遇到同样的问题,解决方案如下:

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

仅当记录中存在 ID 和 TIMENOW 时,具有 attribute_exists 的 ConditionExpression 参数才会删除。