我已经创建了一个DynamoDB表,在我的Python代码中,我将资源初始化如下:
self.dynamodb = self.session.resource('dynamodb').Table('aws-ci')
该表只有一个索引/键,名称为environment
。我正在尝试PUT
进入它,一个对象如下:
{
"environment": "beta",
"X": {
"current_sha": "sha1",
"deployed": true,
"prev_sha": "sha2",
"status": "inactive"
},
"Y-Z": {
"current_sha": "sha1",
"deployed": false,
"prev_sha": "sha2",
"status": "active"
}
}
其中,X
和Y-Z
是微服务的名称。我的插入代码如下:
def put_service_data(self, environment, service_name, service_data, status = None):
get_previous = self.dynamodb.get_item(
Key = {
'environment': environment
}
).get(service_name)
service_data['prev'] = get_previous and get_previous.get('current_sha') or 'NULL'
if status == 'rollback' and get_previous:
service_data['current'] = get_previous.get('current_sha')
service_data['prev'] = get_previous.get('prev_sha')
set_query = "SET {0}.current_sha = :current, {0}.prev_sha = :prev, {0}.deployed = :is_deployed, {0}.current_status = :status".format(service_name)
updated = self.dynamodb.update_item(
Key = {
'environment': environment
},
UpdateExpression = set_query,
ExpressionAttributeValues = {
':current': service_data.get('current'),
':prev': service_data.get('prev'),
':status': service_data.get('status'),
':is_deployed': service_data.get('deployed')
},
ReturnValues = "ALL_NEW"
)
return updated
以前,我没有{0}.current_status
,而是{0}.status
,但这引发了以下错误:
调用时发生错误(
ValidationException
)UpdateItem
操作:UpdateExpression
无效:属性名称为 保留关键字;保留关键字:status
无论如何,我将该属性名称更改为current_status
并再次尝试插入,只是这次我收到了:
调用时发生错误(
ValidationException
)UpdateItem
操作:更新中提供的文档路径 表达式对于更新无效
尝试设置服务 X 的属性时,以及尝试 Y-Z 时的以下内容:
调用时发生错误(
ValidationException
)UpdateItem
操作:无效UpdateExpression
:语法错误; 令牌:“ - ”,附近:“Y-Z”
我目前无法理解update_item
调用应如何运作。
答案 0 :(得分:9)
set_query = "SET #service_name.current_sha = :current, #service_name.prev_sha = :prev, #service_name.deployed = :is_deployed, #service_name.current_status = :current_status"
updated = self.dynamodb.update_item(
Key = {
'environment': environment
},
UpdateExpression = set_query,
ExpressionAttributeValues = {
':current': service_data.get('current'),
':prev': service_data.get('prev'),
':current_status': service_data.get('status'),
':is_deployed': service_data.get('deployed')
},
ExpressionAttributeNames = {
'#service_name': service_name,
},
ReturnValues = "ALL_NEW"
)