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 在项目不存在时返回错误?
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)
如果有人遇到同样的问题,解决方案如下:
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 参数才会删除。
| 归档时间: |
|
| 查看次数: |
7525 次 |
| 最近记录: |