Amazon Lambda 写入 DynamoDB

Amazon Lambda writing to DynamoDB

我是 dynamoDB 的新手,我正在尝试使用 Lambda 将一些数据写入 table。 到目前为止我有这个:

'AddFood': function () {

    var FoodName = this.event.request.intent.slots.FoodName.value;
    var FoodCalories = this.event.request.intent.slots.FoodCalories.value;
    console.log('FoodName : ' + FoodName);

    const params = {
        TableName: 'Foods',
        Item: {
            'id': {"S": 3},
            'calories': {"S": FoodCalories},
            'food': {"S": FoodName}
            }
    };

    writeDynamoItem(params, myResult=>{
        var say = '';

        say = myResult;

        say = FoodName + ' with ' + FoodCalories + ' calories has been added ';
        this.response.speak(say).listen('try again');
        this.emit(':responseReady');

    });

    function writeDynamoItem(params, callback) {

        var AWS = require('aws-sdk');
        AWS.config.update({region: AWSregion});

        var docClient = new AWS.DynamoDB();

        console.log('writing item to DynamoDB table');

        docClient.putItem(params, function (err, data) {
            if (err) {
                callback(err, null)
            } else {
               callback(null, data)
            }
        });
    }
}

有谁知道为什么数据没有出现在数据库中? 我检查了 IAM,策略设置为 AmazonDynamoDBFullAccess。

要从 Lambda 函数(使用 Python)写入 DynamoDB,您必须使用 boto3 包并加载 dynamodb 资源:

希望这会有所帮助,它正在写入事件中的食物和卡路里,并使用生成的 uuid 写入它们

import boto3
import os
import uuid

def writeToDynamo(event, context):

    recordId = str(uuid.uuid4())
    voice = event["food"]
    text = event["calories"]

    print('Generating new DynamoDB record, with ID: ' + recordId)
    print('Input food: ' + food)
    print('Input calories: ' + calories)

    #Creating new record in DynamoDB table
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table(os.environ['DB_TABLE_NAME'])
    table.put_item(
        Item={
            'id' : recordId,
            'food' : food,
            'calories' : calories
        }
    )

    return recordId

对写入函数进行一些更改后,以下代码允许我将项目写入数据库:

函数 writeDynamoItem(参数,回调){

const AWS = require('aws-sdk');
AWS.config.update({region: AWSregion});

const docClient = new AWS.DynamoDB.DocumentClient({region: 'eu-west-1'});

console.log('writing item to DynamoDB table');

docClient.put(params, function (err, data) {
    if (err) {
        callback(err, null)
         console.error("Unable to write item. Error JSON:", JSON.stringify(err, null, 2))
    } else {
       callback(null, data)
    }
});

}