2016-05-04 39 views
1

我現在只使用Amazon AWS DynamoDB。在未來我想把項目放在我的表中,但只是如果具有相同鍵的項目不存在,以便我不覆蓋現有值。你知道我是怎麼做到的?我的代碼:DynamoDB:我如何做一個putItem,但只是如果在Python中不存在鍵?

from __future__ import print_function # Python 2/3 compatibility 
import boto3 
import json 
import decimal 

# Helper class to convert a DynamoDB item to JSON. 
class DecimalEncoder(json.JSONEncoder): 
    def default(self, o): 
     if isinstance(o, decimal.Decimal): 
      if o % 1 > 0: 
       return float(o) 
      else: 
       return int(o) 
     return super(DecimalEncoder, self).default(o) 

dynamodb = boto3.resource('dynamodb', region_name='eu-central-1') 

table = dynamodb.Table('Movies') 

title = "The Big New Movie" 
year = 2015 

response = table.put_item(
    Item={ 
     'year': year, 
     'title': title, 
     'info': { 
      'plot':"Nothing happens at all.", 
      'rating': decimal.Decimal(0) 
     } 
    }, 
) 

我聽說過ConditionExpression。但我不知道如何添加這個。它不工作是這樣的:

response = table.put_item(
    Item={ 
     'year': year, 
     'title': title, 
     'info': { 
      'plot':"Nothing happens at all.", 
      'rating': decimal.Decimal(0) 
     } 
    }, 
    ConditionExpression = "attribute_not_exists", 
) 

因爲當時我得到以下錯誤:

Traceback (most recent call last): 
    File "/Users/iTom/ownCloud/Documents/Workspace/PyCharm/DynamoDBTest/MoviesItemOps1.py", line 32, in <module> 
ConditionExpression = "attribute_not_exists", 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boto3/resources/factory.py", line 518, in do_action 
response = action(self, *args, **kwargs) 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boto3/resources/action.py", line 83, in __call__ 
response = getattr(parent.meta.client, operation_name)(**params) 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 252, in _api_call 
return self._make_api_call(operation_name, kwargs) 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 542, in _make_api_call 
raise ClientError(parsed_response, operation_name) 
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Syntax error; token: "<EOF>", near: "attribute_not_exists" 

回答

2

您的條件表達式指定屬性,像這樣:

ConditionExpression = "attribute_not_exists(title)" 
相關問題