【发布时间】:2023-04-09 21:59:01
【问题描述】:
我想在支持部分更新的 FastAPI 中实现 put 或 patch 请求。 The official documentation 真的很混乱,我不知道如何提出请求。 (我不知道items 在文档中,因为我的数据将通过请求的正文而不是硬编码的字典传递)。
class QuestionSchema(BaseModel):
title: str = Field(..., min_length=3, max_length=50)
answer_true: str = Field(..., min_length=3, max_length=50)
answer_false: List[str] = Field(..., min_length=3, max_length=50)
category_id: int
class QuestionDB(QuestionSchema):
id: int
async def put(id: int, payload: QuestionSchema):
query = (
questions
.update()
.where(id == questions.c.id)
.values(**payload)
.returning(questions.c.id)
)
return await database.execute(query=query)
@router.put("/{id}/", response_model=QuestionDB)
async def update_question(payload: QuestionSchema, id: int = Path(..., gt=0),):
question = await crud.get(id)
if not question:
raise HTTPException(status_code=404, detail="question not found")
## what should be the stored_item_data, as documentation?
stored_item_model = QuestionSchema(**stored_item_data)
update_data = payload.dict(exclude_unset=True)
updated_item = stored_item_model.copy(update=update_data)
response_object = {
"id": question_id,
"title": payload.title,
"answer_true": payload.answer_true,
"answer_false": payload.answer_false,
"category_id": payload.category_id,
}
return response_object
如何完成我的代码以在此处获得成功的部分更新?
【问题讨论】:
-
stored_item_data 是您进入问题变量的数据。基本上,如果您的问题是带有旧值的 dict,请将旧值替换为新值(有效负载变量),并将整个行替换为数据库中的组合值(旧值和新值)。文档显示了一个一般情况,您应该自己在数据库上实现更新,而不是 fastapi
标签: python python-3.x sqlalchemy fastapi pydantic