学习fastapi框架中的response_model用法

学习fastapi框架中的response_model用法

接口函数如下图:

@router.get('/user_info',response_model=UserList)
async def user_info(db : Session = Depends(get_db)):
    # try:
    #     print(1+'1')
    user_info= db.query(User).all()
    # user_info= db.query(User).first()
    user=[
        {
            "id": 1,
            "name": "Python"
        },
        {
            "id": None,
            "name": None
        }]
    # return user_info
    return {"user_info":user_info,"user":user}

然后需要创建一个公用的py文件定义一个UserList类

UserList类如下图

class UserBase(BaseModel):
    id : int
    email: str
    # hashed_password : str

    class Config:
        orm_mode = True

class UserBase1(BaseModel):
    id: Optional[int] = None
    name: Optional[str] = None
    # hashed_password : str

    class Config:
        orm_mode = True  # 为Pydantic开启验证

class UserList(BaseModel):
    user_info:List[UserBase]
    user: List[UserBase1]

User模型如下图

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    email = Column(String(32), unique=False, index=True)
    hashed_password = Column(String(32))
    is_active = Column(Boolean, default=True)

    
    def to_dict(self):
        model_dict = dict(self.__dict__)
        del model_dict['_sa_instance_state']
        return model_dict


    # 多个对象
    def dobule_to_dict(self):
        result = {}
        for key in self.__mapper__.c.keys():
            if getattr(self, key) is not None:
                result[key] = str(getattr(self, key))
            else:
                result[key] = getattr(self, key)
        return result

def to_json(all_vendors):
    if isinstance(all_vendors[0],Iterable):
        v = [[i.dobule_to_dict() for i in ven  if i != None] for ven in all_vendors]
    else:
        v = [ven.dobule_to_dict() for ven in all_vendors]
    return v

然后通过postman测试接口如下

{
    "user_info": [
        {
            "id": 1,
            "email": "123@qq.com"
        },
        {
            "id": 10,
            "email": "1"
        },
        {
            "id": 11,
            "email": "0@qq.com"
        },
        {
            "id": 12,
            "email": "1@qq.com"
        },
        {
            "id": 14,
            "email": "3@qq.com"
        },
        {
            "id": 15,
            "email": "4@qq.com"
        },
        {
            "id": 16,
            "email": "5@qq.com"
        },
        {
            "id": 17,
            "email": "6@qq.com"
        },
        {
            "id": 18,
            "email": "7@qq.com"
        },
        {
            "id": 19,
            "email": "8@qq.com"
        },
        {
            "id": 20,
            "email": "9@qq.com"
        },
        {
            "id": 356,
            "email": "456@qq.com"
        },
        {
            "id": 357,
            "email": "456@qq.com"
        },
        {
            "id": 358,
            "email": "456@qq.com"
        },
        {
            "id": 359,
            "email": "456@qq.com"
        },
        {
            "id": 360,
            "email": "456@qq.com"
        }
    ],
    "user": [
        {
            "id": 1,
            "name": "Python"
        },
        {
            "id": null,
            "name": null
        }
    ]
}

这样就可以完全做到自定义需要返回的数据类型字段了,如果没有这个功能,会把模型中的所有字段都会返回,所以通过这个功能,可以根据实际需求返回相应的字段

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值