11.FastAPI模型与字典
11.1Pydantic 的 .dict()
Pydantic 模型的 .dict()方法返回一个拥有模型数据的 dict。 代码如下:
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Language(BaseModel): id: str name: str year: int rank: int @app.get(path='/test') async def test(): python = Language(id='L1', name='python', year=2021, rank=1) print(type(python)) print(type(python.dict())) print(python.dict()) return python
执行请求:
curl http://127.0.0.1:8000/test {"id":"L1","name":"python","year":2021,"rank":1}
print语句的输出:
<class 'main.Language'> <class 'dict'> {'id': 'L1', 'name': 'python', 'year': 2021, 'rank': 1}
11.2dict解包
反过来,我们将类似与Pydantic 模型的字典数据以 **字典变量 的形式传递给一个函数或者类,python会对其解包,会将字典的键和值作为关键字参数直接传递。代码如下:
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Language(BaseModel): id: str name: str year: int rank: int @app.get(path='/test') async def test(): python = { 'id': 'L1', 'name': 'python', 'year': 2021, 'rank': 1 } print(type(python)) print(type(Language(**python))) print(Language(**python)) return python
执行请求:
curl http://127.0.0.1:8000/test {"id":"L1","name":"python","year":2021,"rank":1}
print输出:
<class 'dict'> <class 'main2.Language'> id='L1' name='python' year=2021 rank=1
在实际应用开发过程中,Pydantic 模型与字典之间的相互转换是非常有价值和意义的,如:将请求体转为字典,然后将字典写入数据表等。