使用fastAPI/mongodb设置PUT方法中的可选参数



我试图从我的API设置一个PUT方法中的Optional一些参数。使用fastAPImongodb,我建立了一个简单的API来插入学生和删除学生,现在我希望允许我更新条目,但不是强制性的"params"

我已经检查了这个Fastapi: put方法,看起来像我正在寻找mongodb。

art049的响应看起来类似于我已经在我的@api_router.put('/update-student/{id}', tags=['Student'])MongoDb中使用FastAPI

以我的问题为例,我有这样的结构:

:

class Student(BaseModel):
age:int
name:str
address:str
class UpdateStudent(BaseModel):
age: Optional[int] = None
name: Optional[str] = None
address: Optional[str] = None

:

def serializeDict(a) -> dict:
return {**{i:str(a[i]) for i in a if i=='_id'},**{i:a[i] for i in a if i!='_id'}}
def serializeList(entity) -> list:
return [serializeDict(a) for a in entity]
<<p>路线/strong>:
@api_router.post('/create-student', tags=['Students'])
async def create_students(student: Student):
client.collegedb.students_collection.insert_one(dict(student))
return serializeList(client.collegedb.students_collection.find())

我也知道我可以用这种方式更新条目而不会出现问题:

@api_router.put('/update-student/{id}', tags=['Student'])
async def update_student(id,ustudent: UpdateStudent):
client.collegedb.students_collection.find_one_and_update({"_id":ObjectId(id)},{
"$set":dict(ustudent)
})
return serializeDict(client.collegedb.students_collection.find_one({"_id":ObjectId(id)}))

我的问题,你可以看到我的模型,我需要一种方法来验证哪些参数被修改,并只更新那些:例如,如果我现在只更新年龄;由于其他参数不是必需的,name和address将被存储为None(实际上是null),因为我在我的模型中设置了这一点。

也许我可以这样做:

if ustudent.age != None:
students_collection[ObjectId(id)] = ustudent.age
if ustudent.name != None:
students_collection[ObjectId(id)] = ustudent.name
if ustudent.address != None:
students_collection[ObjectId(id)] = ustudent.address

我知道我可以在一个简单的字典中使用这个,但从来没有在mongodb的集合中尝试过,因为pydantic不支持ObjectId的迭代,这就是为什么创建serializeDict

如果有人能给我一个提示,我将非常感激

您可以使用FastAPI文档中建议的exclude_unset=True参数:

@api_router.put('/update-student/{id}', tags=['Student'])
async def update_student(id,ustudent: UpdateStudent):
client.collegedb.students_collection.find_one_and_update({"_id":ObjectId(id)},{
"$set":ustudent.dict(exclude_unset=True)
})
return serializeDict(client.collegedb.students_collection.find_one({"_id":ObjectId(id)}))

这是导出Pydantic模型的文档。

最新更新