Skip to main content
 首页 » 编程设计

Python之put_item() S3、Lambda、DynamoDB——发生错误(ValidationException)

2024年12月31日6telwanggs

我将 Python 与 AWS S3、lambda 和 DynamoDB 结合使用。我将 lambda 函数设置为触发器。当我将 .json 文件放入我的 S3 存储桶时,它会激活。

当我的函数激活时,一旦它到达我应该将 json 对象存储在我的 dynamodb 表中的 put_item 函数调用,它就会出错。

错误文本:

[ERROR] ClientError: An error occurred (ValidationException) 
when calling the PutItem operation: One or more parameter values 
were invalid: Missing the key test in the item 

我曾尝试更改 table.put_item(TableName='testTable', Item = jsonDict) 中的参数,但我之前关注的文档仅将一个参数传递给此函数。

如有任何建议或帮助,我们将不胜感激。

我的代码声明:

import boto3 
import json 
 
s3_client = boto3.client('s3') 
dynamodb = boto3.resource('dynamodb') 
 
def lambda_handler(event, context): 
    bucket = event['Records'][0]['s3']['bucket']['name'] 
    json_file_name = event['Records'][0]['s3']['object']['key'] 
    json_object = s3_client.get_object(Bucket=bucket,Key=json_file_name) 
    jsonFileReader = json_object['Body'].read() 
    jsonDict = json.loads(jsonFileReader) 
    table = dynamodb.Table('test') 
    table.put_item(Item = jsonDict) 
 
    return 'Hello from lambda' 

云观察日志:

[ERROR] ClientError: An error occurred (ValidationException) when 
calling the PutItem operation: One or more parameter values were 
invalid: Missing the key test in the item 
Traceback (most recent call last): 
 
  File "/var/task/lambda_function.py", line 14, in lambda_handler 
    response = table.put_item(Item = jsonDict) 
  File "/var/runtime/boto3/resources/factory.py", line 520, in do_action 
    response = action(self, *args, **kwargs) 
  File "/var/runtime/boto3/resources/action.py", line 83, in __call__ 
    response = getattr(parent.meta.client, operation_name)(**params) 
  File "/var/runtime/botocore/client.py", line 320, in _api_call 
    return self._make_api_call(operation_name, kwargs) 
  File "/var/runtime/botocore/client.py", line 623, in _make_api_call 
    raise error_class(parsed_response, operation_name) 

编辑:

我使用“test”主键和“test”表名创建了我的表,将所有其他设置保留为 AWS dynamo 表创建 GUI 中的默认设置。

json文件内容:

{ "test": { "name": "Cody", "age": 27, "car": true }

请您参考如下方法:

您正在尝试使用 {"name": "Cody", "age": 27, "car": true} 作为主键的值。在 DynamoDB 中,主(分区)键只能是 type string, binary or number .

例如,使用 {"test": "Cody", "age": 27, "car": True} 作为 Item 的参数 put_item 会起作用。

或者,如果您将表中的分区键名称更改为 name,调用 table.put_item(Item=jsonDict['test']) 也会执行把戏。