学习fastapi框架中的response_model用法

本文介绍如何使用FastAPI框架的response_model特性来自定义接口返回的数据类型和字段,包括定义UserList类及其实现,以及如何通过postman进行接口测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习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
        }
    ]
}

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

### 使用 FastAPI 进行后端开发 #### 创建项目结构 为了更好地组织代码,在创建一个新的 FastAPI 应用程序时建议建立清晰的文件夹结构。通常情况下会有一个 `main.py` 文件作为入口点,以及可能存在的其他模块来分离逻辑。 ```python from fastapi import FastAPI, Depends app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello World"} ``` 这段简单的例子展示了如何初始化一个 FastAPI 实例并定义了一个根路径处理器[^2]。 #### 定义依赖项和服务注入 通过 `Depends()` 函数可以在路由之间共享状态或配置参数而无需重复编写相同的代码片段。这有助于保持应用程序组件之间的松耦合关系。 ```python def get_db(): db = DBSession() try: yield db finally: db.close() @app.post("/items/", response_model=Item) async def create_item(item: Item, db: Session = Depends(get_db)): ... ``` 上述代码段说明了怎样利用依赖注入机制引入数据库连接池或其他外部资源到请求处理过程中[^1]。 #### 自动生成交互式 API 文档 得益于 OpenAPI 和 Swagger UI 技术的支持,每当开发者完成新的 RESTful 接口实现之后,FastAPI 都能够自动生成美观易读且功能齐全的在线帮助页面供测试人员查阅和调用接口方法。 访问 `/docs` 或者 `/redoc` 即可查看这些动态生成出来的文档界面。 #### 异常处理与安全性考量 对于生产环境下的应用而言,合理的错误反馈机制不可或缺;同时还需要考虑身份验证、授权等问题以保护敏感数据不被非法获取。为此 FastAPI 提供了一系列内置工具箱使得这些问题变得简单明了。 ```python from fastapi.security import OAuth2PasswordBearer oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/users/me") async def read_users_me(token: str = Depends(oauth2_scheme)): user = fake_decode_token(token) return user ``` 此部分介绍了基于OAuth2协议的身份认证方案及其集成方式。 #### 性能优化技巧 由于采用了协程技术栈(即 async/await),因此理论上讲只要合理安排 I/O 密集型操作就能显著提升吞吐量表现。另外还可以借助第三方库如 Pydantic 来简化模型校验流程从而减少不必要的计算开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值