Example of update_item in dynamodb boto3

后端 未结 5 750
陌清茗
陌清茗 2020-12-14 00:10

Following the documentation, I\'m trying to create an update statement that will update or add if not exists only one attribute in a dynamodb table.

I\'m trying this

5条回答
  •  暖寄归人
    2020-12-14 00:53

    If you don't want to check parameter by parameter for the update I wrote a cool function that would return the needed parameters to perform a update_item method using boto3.

    def get_update_params(body):
        """Given a dictionary we generate an update expression and a dict of values
        to update a dynamodb table.
    
        Params:
            body (dict): Parameters to use for formatting.
    
        Returns:
            update expression, dict of values.
        """
        update_expression = ["set "]
        update_values = dict()
    
        for key, val in body.items():
            update_expression.append(f" {key} = :{key},")
            update_values[f":{key}"] = val
    
        return "".join(update_expression)[:-1], update_values
    

    Here is a quick example:

    def update(body):
        a, v = get_update_params(body)
        response = table.update_item(
            Key={'uuid':str(uuid)},
            UpdateExpression=a,
            ExpressionAttributeValues=dict(v)
            )
        return response
    

提交回复
热议问题