如何基于dataclass创建Python泛型自定义类型用于FastAPI统一响应?
实现FastAPI统一泛型响应格式的方法
完全可以实现这种自定义泛型类型,核心是利用Python的泛型类型系统结合dataclass来定义通用响应结构,无需为每个数据类单独创建响应类。
具体实现步骤
导入必要的类型工具
需要从typing模块导入泛型相关工具,搭配dataclass和FastAPI:from dataclasses import dataclass from typing import Generic, TypeVar from fastapi import FastAPI定义泛型类型变量
声明一个可代表任意类型的变量,后续用来绑定具体的数据类:T = TypeVar('T')定义泛型响应类
让Response类继承Generic[T],并将data字段的类型指定为T:@dataclass class Response(Generic[T]): status: str = "OK" data: T在FastAPI接口中使用
现在就可以直接用Response[具体数据类]作为接口的返回类型标注,同时指定response_model让FastAPI自动处理序列化和文档生成:@dataclass class Customer: name: str age: int app = FastAPI() @app.get("/customer/{customer_id}", response_model=Response[Customer]) def get_customer(customer_id: int) -> Response[Customer]: # 模拟业务逻辑获取数据 customer_data = Customer(name="张三", age=30) return Response(data=customer_data)
关键说明
- FastAPI能正确识别这种泛型结构,自动生成符合要求的OpenAPI文档,同时对返回数据做校验和序列化。
- 若使用Python 3.8及以下版本,需要从
typing_extensions模块导入Generic和TypeVar来兼容泛型特性。
内容的提问来源于stack exchange,提问作者GuruYaya
相关产品推荐
相关产品推荐

