python dynamodb参数的类型无效

2024-09-30 20:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过CDK创建dynamodb表

    const table = new dynamodb.Table(this, "my-table", {
      tableName: StackConfiguration.tableName,
      partitionKey: { name: "file_id", type: dynamodb.AttributeType.STRING },
    });

    dynamoReplayTable.addGlobalSecondaryIndex({
      indexName: "processed",
      # ideally would like boolean here but doesn't seem to be an option
      partitionKey: { name: "processed", type: dynamodb.AttributeType.STRING },
    });

然后使用boto3,我像这样将数据插入表中

    failedRecord = {
        "file_id": str(file_id),
        "processed": "false",
        "payload": str(payload),
        "headers": str(headers),
    }

    table.put_item(Item=failedRecord)

然后,我有另一个服务读取项目,然后处理,我想将作为全局二级索引的processed字段更新为true

我现在有这个密码

    table.update_item(
        Key={"file_id": file_id}, AttributeUpdates={"processed": "true"},
    )

但这会导致以下错误

Parameter validation failed:
Invalid type for parameter AttributeUpdates.processed, value: true, type: <class 'str'>, valid types: <class 'dict'>

Tags: nameidtruestringtypetabledynamodbfile
2条回答

DynamoDB以一种非常特殊的方式处理dat类型,您可以找到更多信息herehere

在您的例子中,问题在于update命令的值"true"。使用类型可能很棘手,boto3提供了一个TypeSerializerTypeDeserializer可用于为您处理转换:

import boto3
from boto3.dynamodb.types import TypeSerializer

serializer = TypeSerializer()

my_single_value = "processed"

print(serializer.serialize(my_single_value))
# {'S': 'processed'}

my_dict_object = {
  "processed": "true"
}

print({k: serializer.serialize(v) for k, v in my_dict_object.items()})
# {'processed': {'S': 'true'}}

用下面的代码解决了这个问题

    table.update_item(
        Key={"file_id": file_id},
        UpdateExpression="SET processed_status = :processed",
        ExpressionAttributeValues={":processed": "true"},
    )

相关问题 更多 >