Tom*_*ere 3 python amazon-web-services amazon-dynamodb
我现在刚使用 Amazon AWS DynamoDB。在未来,我想将 Items 放在我的表中,但前提是具有相同键的 Item 不存在,这样我就不会覆盖现有值。你知道我是怎么做到的吗?我的代码:
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)
}
},
)
Run Code Online (Sandbox Code Playgroud)
我听说过 ConditionExpression。但我不知道如何添加这个。它不是这样工作的:
response = table.put_item(
Item={
'year': year,
'title': title,
'info': {
'plot':"Nothing happens at all.",
'rating': decimal.Decimal(0)
}
},
ConditionExpression = "attribute_not_exists",
)
Run Code Online (Sandbox Code Playgroud)
因为那时我收到以下错误:
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"
Run Code Online (Sandbox Code Playgroud)
您必须在条件表达式中指定一个属性,如下所示:
ConditionExpression = "attribute_not_exists(title)"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4150 次 |
| 最近记录: |