簡體   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