繁体   English   中英

使用事件 ['body'] 使用 Python Lambda 在 DynamoDB 中动态插入/更新项目

[英]Dynamically Insert/Update Item in DynamoDB With Python Lambda using event['body']

我正在处理 lambda function,它从 API 网关调用并更新 dynamoDB 中的信息。 我有一半的工作非常动态,而且我有点坚持更新。 这是我正在使用的:

分区键为guild_id的 dynamoDB 表

我的虚拟 json 代码我正在使用:

{
  "guild_id": "126",
  "guild_name": "Posted Guild",
  "guild_premium": "true",
  "guild_prefix": "z!"
}

最后是 lambda 代码:

import json
import boto3

def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("guildtable")
    itemData = json.loads(event['body'])
    
    guild = table.get_item(Key={'guild_id':itemData['guild_id']})
    
    #If Guild Exists, update
    if 'Item' in guild:
      table.update_item(Key=itemData)
      
      responseObject = {}
      responseObject['statusCode'] = 200
      responseObject['headers'] = {}
      responseObject['headers']['Content-Type'] = 'application/json'
      responseObject['body'] = json.dumps('Updated Guild!')
      
      return responseObject
    
    #New Guild, Insert Guild
    table.put_item(Item=itemData)
    
    responseObject = {}
    responseObject['statusCode'] = 200
    responseObject['headers'] = {}
    responseObject['headers']['Content-Type'] = 'application/json'
    responseObject['body'] = json.dumps('Inserted Guild!')
      
    return responseObject

插入部分工作得很好,我如何用更新项目完成类似的方法? 我希望它尽可能动态,这样我就可以向它抛出任何 json 代码(在合理范围内)并将其存储在数据库中。 我希望我的更新方法考虑到在路上添加字段并处理这些字段

我收到以下错误:

Lambda execution failed with status 200 due to customer function error: An error occurred (ValidationException) when calling the UpdateItem operation: The provided key element does not match the schema. 

“提供的键元素与架构不匹配”错误意味着Key (= 主键)有问题。 您的模式的主键是guild_id: string 非键属性属于AttributeUpdate参数。 请参阅文档

您的项目数据itemdata包含非关键属性。 还要确保guild_id是字符串"123"而不是数字类型123

goodKey={"guild_id": "123"}

table.update_item(Key=goodKey, UpdateExpression="SET ...")

文档有完整的update_item示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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