检查dynamo db表是否存在属性,如果属性存在则因为原因而失败 - boto

时间:2017-01-19 21:15:15

标签: python python-2.7 amazon-dynamodb boto boto3

我使用boto:

跟随python代码
import boto3

# Get the service resource.
dynamodb = boto3.resource('dynamodb', region_name='us-west-2')

# Instantiate a table resource object without actually
# creating a DynamoDB table. Note that the attributes of this table
# are lazy-loaded: a request is not made nor are the attribute
# values populated until the attributes
# on the table resource are accessed or its load() method is called.
table = dynamodb.Table('djin-dev-genesis')

def addtodatabase(appname, chef_max, arp_score):

    response = table.get_item(Key={'appname': str(appname)})
    if 'Item' not in response.keys():
        print "partititon key (appname) not found, creating a new item in dynamo db with the key"
        table.put_item(
           Item={
                'appname': appname,
                'chef_max': True,
                'arp_score': '110'
            }
        )
    else:
        print "partition key = "+str(appname)+" found, here is the item dict : "+str(response['Item'])

我希望在else场景中查看(如果键存在),是否已存在任何属性值且匹配。在那种情况下,我想失败的理由,否则更新属性。

boto中的代码是什么?

1 个答案:

答案 0 :(得分:0)

在像attribute_not_exists(appname)这样的PutItem调用中使用条件表达式,只允许创建项目(如果该项目尚不存在)。捕获ConditionalCheckFailedException,否则使用GetItem获取项目。