繁体   English   中英

如何修复错误:使用 lambda python 在 dynamodb 中输入项目

[英]how to fix error: input item in dynamodb with lambda python

我在使用 lambda 和 dynamodb 时遇到了一些问题。

这是我的 python 代码:

import json
import boto3

def lambda_handler(event, context):
    client = boto3.client('dynamodb', region_name='ap-northeast-2')
    dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-2')

    response = client.put_item(
        TableName='tablename',
        Item = {
            'key1': 'value1',
            'key2': 'value2',
            'key3': 'value3',
            'key4': 'value4'
                }
        )

这是错误日志:

{
  "errorMessage": "Parameter validation failed:\nInvalid type for parameter Item.key1, value: value1, type: <class 'int'>, valid types: <class 'dict'>\nInvalid type for parameter Item.key2, value: value2, type: <class 'str'>, valid types: <class 'dict'>\nInvalid type for parameter Item.key3, value: value3, type: <class 'str'>, valid types: <class 'dict'>\nInvalid type for parameter Item.key4, value: value4, type: <class 'int'>, valid types: <class 'dict'>",
  "errorType": "ParamValidationError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 8, in lambda_handler\n    response = client.put_item(\n",
    "  File \"/var/runtime/botocore/client.py\", line 316, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n",
    "  File \"/var/runtime/botocore/client.py\", line 598, in _make_api_call\n    request_dict = self._convert_to_request_dict(\n",
    "  File \"/var/runtime/botocore/client.py\", line 646, in _convert_to_request_dict\n    request_dict = self._serializer.serialize_to_request(\n",
    "  File \"/var/runtime/botocore/validate.py\", line 297, in serialize_to_request\n    raise ParamValidationError(report=report.generate_report())\n"
  ]
}

我搜索了有关参数验证失败的错误,aws 说我必须下载或升级 pip3 和 AWS CLI,所以我这样做了。 但它仍然会出错。

boto3 SDK 提供了两种put_item()方法,一种是客户端级别,一种是资源级别 它们是不同的,特别是您提供项目属性的方式不同。 您使用的是客户端级别的 API,但传递属性就像您使用的是资源级别的 API 一样。

以下是您如何使用资源级别 API:

import boto3

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-2')
    table = dynamodb.table('tablename')

    response = table.put_item(
        Item = {
            'key1': 'value1',
            'key2': 'value2',
            'key3': 'value3',
            'key4': 'value4'
        }
    )

您的语法似乎不正确。 请参阅https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.put_item的示例

response = client.put_item(
    Item={
        'AlbumTitle': {
            'S': 'Somewhat Famous',
        },
        'Artist': {
            'S': 'No One You Know',
        },
        'SongTitle': {
            'S': 'Call Me Today',
        },
    },
    ReturnConsumedCapacity='TOTAL',
    TableName='Music',
)

值不是字符串,而是AttributeValue类型的实例

暂无
暂无

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

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