python - 使用 boto3 有条件地将项目插入到 dynamodb 表中错误属性名称是保留关键字
问题描述
如果项目(状态)不存在,我将调用此函数来放置项目,我在这里指的是:如何使用 boto3 有条件地将项目插入到 dynamodb 表中。
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
这里的问题是状态是一个保留字,因此它失败并出现错误:
[ERROR] ClientError: An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Attribute name is a reserved keyword; reserved keyword: state
有什么建议来处理这个吗?
解决方案
这就是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
推荐阅读
- airflow - 气流 dag 文件未运行
- google-apps-script - 可以从谷歌脚本 API 调用中设置变量吗?
- xpath - 如何使用 xpath 获取没有“\n”的文本?
- c# - 如何在 ASP.NET Core MVC 中使用 ADO.NET 向存储过程添加参数?
- c++ - 从 [[nodiscard]] 中排除函数的返回值
- jquery - 按当前日期过滤 Json 数据
- java - 从 Fused Location Provider 获取 GPS 或网络提供商
- html - 仅更改悬停元素的 SVG 填充
- python - 读取文件类型扩展关联列表
- python - 解析字符串映射正确的标签