Ich benutze Amazon AWS DynamoDB gerade neu. In Zukunft möchte ich Elemente in meine Tabelle legen, aber nur wenn ein Element mit dem gleichen Schlüssel nicht existiert, so dass ich einen vorhandenen Wert nicht überschreibe. Weißt du wie ich das mache? Mein Code:DynamoDB: Wie mache ich ein PutItem aber nur wenn Schlüssel in Python nicht existiert?
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)
}
},
)
Ich hörte von ConditionExpression. Aber ich weiß nicht, wie ich das hinzufügen soll. Es kann so nicht arbeiten:
response = table.put_item(
Item={
'year': year,
'title': title,
'info': {
'plot':"Nothing happens at all.",
'rating': decimal.Decimal(0)
}
},
ConditionExpression = "attribute_not_exists",
)
Denn dann bekomme ich die folgende Fehlermeldung:
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"