FastAPI 显示“msg”:“必填字段”,“类型”:“value_error.missing”

Cro*_*oss 18 python pydantic fastapi

各位晚上好。我正在尝试使用 FastAPI 请求将新用户添加到我的数据库中。当我尝试通过 python 控制台应用程序执行此操作时,FastAPI 向我显示以下消息:

{
     'detail': [
         {
             'loc': ['body', 'nickname'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'password'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'email'],
             'msg': 'field required',
             'type': 'value_error.missing'
         }
    ]
}
Run Code Online (Sandbox Code Playgroud)

但是,当我执行此请求时,/docs一切正常!

这是我的 pydantic 模型:

{
     'detail': [
         {
             'loc': ['body', 'nickname'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'password'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'email'],
             'msg': 'field required',
             'type': 'value_error.missing'
         }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这是我的处理程序:

class GetUserModel(BaseModel):
    nickname: str
    password: str
    email: str

    class Config:
        orm_mode = True
Run Code Online (Sandbox Code Playgroud)

在这里我试图提出一个请求:

@users_router.post("/users/", status_code=200)
def add_new_user(user: GetUserModel, session: Session = Depends(get_session)):
    user.password = bcrypt.hashpw(
        user.password.encode(),
        bcrypt.gensalt()
    )  # password hashing

    new_user = User(**user.dict())
    add(session, new_user)  # adding to database
Run Code Online (Sandbox Code Playgroud)

如果您知道可能出现什么问题,请告诉我,我将非常感激!

Joh*_*fis 3

根据对您问题的评论,为了使您的请求正常工作,您需要使用request参数执行json,就像dataFastAPI 假设您正在发送表单数据一样:

response = requests.post(
    url='http://127.0.0.1:8000/users/',
    json={
        "nickname": "1",
        "password": "1",
        "email": "1"
    }
)
Run Code Online (Sandbox Code Playgroud)

但是,如果您确实想发送表单数据,则需要更改端点以接受Form参数:

@users_router.post("/users/", status_code=200)
def add_new_user(
    nickname: str = Form(),
    password: str = Form(),
    email: str = Form(),
    session: Session = Depends(get_session)
):
    -- Endpoint handling here ---
Run Code Online (Sandbox Code Playgroud)