Jus*_*mas 0 python amazon-web-services amazon-dynamodb boto3 dynamodb-queries
如果项目(状态)不存在,我将调用此函数来放置项目,这是我从这里引用的内容:How do I Conditionally insert an item into a dynamodb table using boto3 ..
def put_items_if_doesnt_exist():
dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
try:
table = dynamodb.Table('awssolutions-ssm-hybrid-table')
response = table.put_item(
Item={
'name':'Execution',
'state': 'Locked',
},
ConditionExpression='attribute_not_exists(state) AND attribute_not_exists(name)'
)
except ClientError as e:
# Ignore the ConditionalCheckFailedException
if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
raise
Run Code Online (Sandbox Code Playgroud)
这里的问题是状态是保留字,因此它失败并出现错误:
[ERROR] ClientError: An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Attribute name is a reserved keyword; reserved keyword: state
Run Code Online (Sandbox Code Playgroud)
有什么建议来处理这个问题吗?
这就是ExpressionAttributeNames进来的地方,他们允许您使用保留名称。您只需添加带有前缀的占位符#并在ExpressionAttributeNames参数中指定其值。
def put_items_if_doesnt_exist():
dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
try:
table = dynamodb.Table('awssolutions-ssm-hybrid-table')
response = table.put_item(
Item={
'name':'Execution',
'state': 'Locked',
},
ConditionExpression='attribute_not_exists(#state) AND attribute_not_exists(#name)',
ExpressionAttributeNames={"#state": "state", "#name": "name"}
)
except ClientError as e:
# Ignore the ConditionalCheckFailedException
if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
raise
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2413 次 |
| 最近记录: |