作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我现在刚刚使用 Amazon AWS DynamoDB。在 Future 中,我想将 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)
}
},
)
我听说过 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"
最佳答案
您必须在条件表达式中指定一个属性,如下所示:
ConditionExpression = "attribute_not_exists(title)"
关于python - 发电机 : How do I do a putItem but just if key doesn't exists in Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37028898/
我是一名优秀的程序员,十分优秀!