简体   繁体   中英

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:

current_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

conditions:

  1. kpi_id = KPI038
  2. metric_id = 'NA'

Table name: CONFIG

partition key: kpi_id

sort key: metric_id

I want to function to update an item in python using boto3.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM