FastAPI中的部分更新部分、FastAPI

2023-09-04 01:57:12 作者:用一个宇宙换一颗红豆

我想在支持部分更新的FastAPI中实现PUT或补丁请求。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

如何在此处完成代码以获得成功的部分更新?

推荐答案

Python中fastapi框架入门

我得到了关于FastAPI的Github问题的答案:

您可以使基类上的字段成为可选的,并创建一个新的QuestionCreate模型来扩展QuestionSchema。例如:

from typing import Optional

class Question(BaseModel):
    title: Optional[str] = None  # title is optional on the base schema
    ...

class QuestionCreate(Question):
   title: str  # Now title is required

Cookiecuter模板here也提供了一些很好的见解。