[英]how to update a value in dynamodb table based on condition using python and boto3?
我想根據以下條件更新 dynamodb (last_run_date) 列中的以下 current_date 值:
current_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
條件:
表名:配置
分區鍵:kpi_id
排序鍵:metric_id
我想 function 使用 boto3 更新 python 中的項目。
我試過的代碼:
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)
答案:這行得通
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.