如何在FastAPI接口中获取PropsCreate类的默认值?
问题描述
我正在使用Python FastAPI,在app/model/props.py文件中定义了如下PropsCreate类(继承自PropsBase):
class PropsCreate(PropsBase): id: str sender: str voice: str provider: Optional[str] destination: str = "/usr/local/"
该类的destination字段设置有默认值。我希望在app/api/endpoint/endpoints.py的如下GET路由中获取这个默认值:
from fastapi.routing import APIRouter from app.models.props import ( PropsBase ) router = APIRouter() @router.get("/getdefaults", response_model=PropsBase) def default_data(): pass
请问如何在该GET路由中从PropsCreate类获取对应的默认值?
解决方案
导入
PropsCreate类
首先修改endpoints.py中的导入语句,把PropsCreate也导入进来——因为默认值是定义在这个子类中的:from app.models.props import PropsBase, PropsCreate获取默认值的两种可行方式
直接读取字段默认值
利用Pydantic模型自带的__fields__属性,无需实例化模型就能直接拿到destination的默认值:@router.get("/getdefaults", response_model=PropsBase) def default_data(): default_dest = PropsCreate.__fields__["destination"].default # 按PropsBase的结构返回数据,若有其他字段需补充对应值 return {"destination": default_dest}通过模型实例获取
使用Pydantic的construct()方法创建实例(该方法会跳过字段验证,适合仅获取默认值的场景),再读取实例的destination属性:@router.get("/getdefaults", response_model=PropsBase) def default_data(): # 必填字段传入临时占位值即可 props_instance = PropsCreate.construct(id="temp", sender="temp", voice="temp") default_dest = props_instance.destination return {"destination": default_dest}
注意:如果PropsBase包含其他必填字段,需要在返回结果中补充对应的值,保证返回数据符合response_model的结构要求。
内容的提问来源于stack exchange,提问作者gourav
相关产品推荐
相关产品推荐

