fastapi response_model Generic自定义返回JSON数组
时间: 2023-11-12 18:05:34 浏览: 194
如果你想要自定义 FastAPI 的 response_model 参数来返回一个 JSON 数组,你可以使用 List[Response[Dict[str, Any]]] 来实现。这里的 Dict[str, Any] 表示返回的 JSON 对象可以包含任意的键值对,具体的键和值可以根据你的需要进行定义,示例代码如下:
```python
from typing import Generic, List, TypeVar, Dict, Any
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
T = TypeVar('T')
class Response(Generic[T]):
data: T
code: int = 0
msg: str = "success"
class User(BaseModel):
name: str
age: int
@app.get("/users/", response_model=List[Response[Dict[str, Any]]])
async def read_users():
users = [{"name": "Alice", "age": 20}, {"name": "Bob", "age": 25}]
response = [Response[Dict[str, Any]](data=user_dict) for user_dict in users]
return response
```
在这个示例代码中,我们使用了一个类似于之前的 Response 泛型类,但是 data 属性的类型是 Dict[str, Any],这样就可以包含任意的键值对。在 read_users 函数中,我们使用了 List[Response[Dict[str, Any]]] 作为 response_model 参数,表示返回一个 Response 泛型类的列表,每个 Response 对象的 data 属性都是一个包含任意键值对的字典。我们根据实际数据构造了一个 Response 泛型类的列表,并将其作为返回值。
使用这种方式可以方便地自定义返回的 JSON 数组,可以根据实际需要定义不同的 Response 类型,以及每个 Response 对象的 data 属性的键值对。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)