[英]how to update a value in dynamodb table based on condition using python and boto3?
I want to update the below current_date value in dynamodb (last_run_date) column based on following conditions:我想根据以下条件更新 dynamodb (last_run_date) 列中的以下 current_date 值:
current_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S') current_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
conditions:条件:
Table name: CONFIG表名:配置
partition key: kpi_id分区键:kpi_id
sort key: metric_id排序键:metric_id
I want to function to update an item in python using boto3.我想 function 使用 boto3 更新 python 中的项目。
The code which I tried:我试过的代码:
current_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
kpi_id = 'KPI038'
metric_id = 'NA'
return_value = "UPDATED_NEW"
table_name = "kpi_metastore_config"
table = dynamodb.Table(table_name)
def update_dynamodb():
try:
response = table.update_item(
Key={
'kpi_id': kpi_id,
'metric_id': metric_id
},
UpdateExpression="set last_run_date = :r",
ConditionExpression=("kpi_id = :num") & ("metric_id = :number"),
ExpressionAttributeValues={
':r' : current_date,
':num': kpi_id,
':number': metric_id
},
ReturnValues=return_value
)
return response
except Exception as error:
logger.error(error)
def lambda_handler(event, context):
response = update_dynamodb()
if __name__ == '__main__':
lambda_handler(event,context)
ANSWER: This works答案:这行得通
dt = datetime.now()
current_date = int(dt.strftime("%Y%m%d%H%M%S"))
kpi_id = 'KPI038'
metric_id = 'NA'
return_value = "UPDATED_NEW"
def lambda_handler(event, context):
response = table.update_item(
Key={
'kpi_id': kpi_id,
'metric_id': metric_id
},
UpdateExpression= "set last_run_date = :r",
ConditionExpression= "kpi_id = :kpi AND metric_id = :metr",
ExpressionAttributeValues={
':r' : current_date,
':kpi': kpi_id,
':metr': metric_id
},
ReturnValues="UPDATED_NEW"
)
return response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.