使用 Boto3,如何将 python 字典存储为 DynamoDb 中的非 PK 属性?
我的CDK
...
this.table = new Table(this, `myTable`, {
partitionKey: {
name: 'id',
type: AttributeType.STRING,
},
});
...
当我尝试向 API 发布请求(使用 FastAPI)时,我收到一条空错误消息。
API方法
@app.post('/create-student/{student_id}')
def create_student(student_id : int, student : Student):
try:
response = db.put_item(Item={
"id": f"{student_id}",
"student": json.dumps(student)
})
return {"response message": response}
except Exception as error:
return {"error message": error}
由于错误信息正在返回,put_item方法无法完成。
我看到的两个缓解措施:
json.dumps(dict)
) 并插入该字符串如果我不想将字典存储为字符串,也许选项 2 是必要的。看来 Ddb 无法“开箱即用”存储地图类型,因为此用例未在 CDK 中声明。
实现这种效果的首选方法是什么?
只要您的辅助属性不是任何索引的一部分,DynamoDB 并不真正关心您在其中放入的内容。看起来您没有在 CDK 中定义任何属性,所以您应该很好。
假设 Python 代码中的
db
是对表资源的引用,并且您希望属性 student
是 DynamoDB 中的 Map,则应传递字典(或 collections.abc.Mapping
的任何其他实例) :
db.put_item(Item={
"id": f"{student_id}",
"student": {"name": "John", "last_name": "Smith}
})
如果您
Student
类型没有子类 Mapping
,您应该以某种方式将其转换为映射。
通过传递
json.dumps(student)
,可以使其成为包含 JSON 文本的字符串。
既然你说你的代码抛出了错误,那么你的变量
student
可能无法序列化为JSON。但无论如何,这并不是你想要的。