gpt4 book ai didi

python - 发电机 : How do I do a putItem but just if key doesn't exists in Python?

转载 作者:行者123 更新时间:2023-12-04 02:12:27 27 4
gpt4 key购买 nike

我现在刚刚使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com