pydantic 模型如何在不实例化 pydantic 的情况下工作 类

how pydantic model works without instantiating pydantic classes

任何人都可以告诉我,下面的 pydantic 模型代码如何在不实例化 UserIn 和 UserOut class 对象的情况下工作?这是 pydantic 图书馆内部处理的事情吗?

from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    full_name: Optional[str] = None


class UserOut(BaseModel):
    username: str
    email: EmailStr
    full_name: Optional[str] = None


class UserInDB(BaseModel):
    username: str
    hashed_password: str
    email: EmailStr
    full_name: Optional[str] = None


def fake_password_hasher(raw_password: str):
    return "supersecret" + raw_password


def fake_save_user(user_in: UserIn):
    hashed_password = fake_password_hasher(user_in.password)
    user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
    print("User saved! ..not really")
    return user_in_db


@app.post("/user/", response_model=UserOut)
async def create_user(user_in: UserIn):
    user_saved = fake_save_user(user_in)
    print(user_saved.__dict__)
    return user_saved

您不需要在代码中实例化对象,因为在这两种情况下,FastAPI 都会自动为 pydantic 模式创建它们。

对于像您示例中的 user_in: UserIn 这样的 Pydantic 模型的端点方法的参数,它被解释为 Request Body, as explained in the docs here. It's worth noting the explanation about how the input data binding works for the endpoint parameters in FastAPI documentation:

  • If the parameter is also declared in the path, it will be used as a path parameter.
  • If the parameter is of a singular type (like int, float, str, bool, etc) it will be interpreted as a query parameter.
  • If the parameter is declared to be of the type of a Pydantic model, it will be interpreted as a request body.

对于端点输出,当你定义response_model时,它也会转换它,as explained in the documentation here:

FastAPI will use this response_model to:

  • Convert the output data to its type declaration.
  • Validate the data.
  • Add a JSON Schema for the response, in the OpenAPI path operation.
  • Will be used by the automatic documentation systems.