FastAPI学习笔记(一)-11.响应模型基本使用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ''' 2 @author:invoker 3 @project:fastapi202108 4 @file: chapter041.py 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/8/5 21:22 8 @version: Python 3.7.8 9 ''' 10 11 from fastapi import APIRouter 12 from pydantic import BaseModel, EmailStr,Field 13 from typing import Optional 14 15 # 路由对象app04 16 app041 = APIRouter() 17 18 """ 19 响应模型 20 """ 21 22 23 # 用户基本信息-基本模型体 24 class UserInfo(BaseModel): 25 username: str 26 email: EmailStr 27 mobile: str = "15900000003" 28 address: str = None 29 full_name: Optional[str] = None 30 31 32 # 输入用户信息-请求模型体 33 class inputUserModel(UserInfo): 34 password: str 35 36 37 # 返回用户信息,响应模型体 38 class returnUserModel(UserInfo): 39 # userId: int=Field(default=1) 40 pass 41 42 43 users = { 44 "user01": {"username": "invoker", "email": "invoker2021@126.com"}, 45 "user02": {"username": "pudge", "email": "pudge@126.com", "mobile": "15900000002", "address": "夜宴", 46 "full_name": "futu pudge"} 47 } 48 49 50 # response_model叫做路径操作(path operation) 51 # response_model_exclude_unset = False 表示返回值设置为空时,返回值会将默认值填充到返回值内。 52 @app041.post('/response_model_1', response_model=returnUserModel, response_model_exclude_unset=False) 53 async def response_model(user: inputUserModel): 54 print(user.password) 55 return users["user01"]
1.以上代码定义了请求模型 inputUserModel 和 响应模型 returnUserModel 2个类。
请求模型:
# 用户基本信息-基本模型体
class UserInfo(BaseModel):
username: str
email: EmailStr
mobile: str = "15900000003"
address: str = None
full_name: Optional[str] = None
# 输入用户信息-请求模型体
class inputUserModel(UserInfo):
password: str
响应模型:
# 用户基本信息-基本模型体
class UserInfo(BaseModel):
username: str
email: EmailStr
mobile: str = "15900000003"
address: str = None
full_name: Optional[str] = None
# 返回用户信息,响应模型体
class returnUserModel(UserInfo):
# userId: int=Field(default=1)
pass
2.定义了返回值 users
3.设置response_model_exclude_unset = False 表示返回值设置为空时,返回值会将默认值填充到返回值内
接口1:/chapter041/response_model_1
返回值:
{ "username": "invoker", "email": "invoker2021@126.com", "mobile": "15900000003", "address": null, "full_name": null }
4.response_model_exclude_unset = True 表示返回值如果为空,则返回空,不会将默认值填写返回
接口2:/chapter041/response_model_2
返回值:
{ "username": "invoker", "email": "invoker2021@126.com" }
5.合并模型Union
接口3:/chapter041/response_model_3/attributes
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ''' 2 @author:invoker 3 @project:fastapi202108 4 @file: chapter041.py 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/8/5 21:22 8 @version: Python 3.7.8 9 ''' 10 11 from fastapi import APIRouter 12 from pydantic import BaseModel, EmailStr, Field 13 from typing import Optional, Union 14 15 # 路由对象app04 16 app041 = APIRouter() 17 18 """ 19 响应模型 20 """ 21 22 23 # 用户基本信息-基本模型体 24 class UserInfo(BaseModel): 25 username: str 26 email: EmailStr 27 mobile: str = "15900000003" 28 address: str = None 29 full_name: Optional[str] = None 30 31 32 # 输入用户信息-请求模型体 33 class inputUserModel(UserInfo): 34 password: str 35 36 37 # 返回用户信息,响应模型体 38 class returnUserModel(UserInfo): 39 # userId: int=Field(default=1) 40 pass 41 42 43 users = { 44 "user01": {"username": "invoker", "email": "invoker2021@126.com"}, 45 "user02": {"username": "pudge", "email": "pudge@126.com", "mobile": "15900000002", "address": "夜宴", 46 "full_name": "futu pudge"} 47 } 48 49 50 # response_model叫做路径操作(path operation) 51 # response_model_exclude_unset = False 表示返回值设置为空时,返回值会将默认值填充到返回值内。 52 @app041.post('/response_model_1', response_model=returnUserModel, response_model_exclude_unset=False) 53 async def response_model(user: inputUserModel): 54 print(user.password) 55 return users["user01"] 56 57 58 # response_model_exclude_unset = True 表示返回值如果为空,则返回空,不会将默认值填写返回。 59 @app041.post('/response_model_2', response_model=returnUserModel, response_model_exclude_unset=True) 60 async def response_model(user: inputUserModel): 61 print(user.password) 62 return users["user01"] 63 64 65 @app041.post( 66 '/response_model_3/attributes', 67 # 将请求模型和返回模型合并 68 response_model=Union[inputUserModel, returnUserModel], 69 response_model_exclude_unset=True 70 ) 71 async def reponse_model_attributes(user: inputUserModel): 72 # 小技巧,删除掉password 73 del user.password 74 return user
from typing import Union
小技巧,去掉密码,使用del user.password
返回值:
{ "username": "invoker", "email": "user@example.com", "mobile": "15900000003", "address": "填在" }
6.模型技巧2 List+response_model_exclude,response_model_include
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ''' 2 @author:invoker 3 @project:fastapi202108 4 @file: chapter041.py 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/8/5 21:22 8 @version: Python 3.7.8 9 ''' 10 11 from fastapi import APIRouter 12 from pydantic import BaseModel, EmailStr, Field 13 from typing import Optional, Union, List 14 15 # 路由对象app04 16 app041 = APIRouter() 17 18 """ 19 响应模型 20 """ 21 22 23 # 用户基本信息-基本模型体 24 class UserInfo(BaseModel): 25 username: str 26 email: EmailStr 27 mobile: str = "15900000003" 28 address: str = None 29 full_name: Optional[str] = None 30 31 32 # 输入用户信息-请求模型体 33 class inputUserModel(UserInfo): 34 password: str 35 36 37 # 返回用户信息,响应模型体 38 class returnUserModel(UserInfo): 39 # userId: int=Field(default=1) 40 pass 41 42 43 users = { 44 "user01": {"username": "invoker", "email": "invoker2021@126.com"}, 45 "user02": {"username": "pudge", "email": "pudge@126.com", "mobile": "15900000002", "address": "夜宴", 46 "full_name": "futu pudge"} 47 } 48 49 50 # response_model叫做路径操作(path operation) 51 # response_model_exclude_unset = False 表示返回值设置为空时,返回值会将默认值填充到返回值内。 52 @app041.post('/response_model_1', response_model=returnUserModel, response_model_exclude_unset=False) 53 async def response_model(user: inputUserModel): 54 print(user.password) 55 return users["user01"] 56 57 58 # response_model_exclude_unset = True 表示返回值如果为空,则返回空,不会将默认值填写返回。 59 @app041.post('/response_model_2', response_model=returnUserModel, response_model_exclude_unset=True) 60 async def response_model(user: inputUserModel): 61 print(user.password) 62 return users["user01"] 63 64 65 @app041.post( 66 '/response_model_3/attributes', 67 # 将请求模型和返回模型合并 68 response_model=Union[inputUserModel, returnUserModel], 69 response_model_exclude_unset=True 70 ) 71 async def reponse_model_attributes(user: inputUserModel): 72 # 小技巧,删除掉password 73 del user.password 74 return user 75 76 77 @app041.post( 78 '/response_model_4/List', 79 response_model=List[returnUserModel], 80 response_model_exclude_unset=True, 81 response_model_include=['username', 'email','password'], 82 response_model_exclude=['mobile', 'address'] 83 84 ) 85 async def reponse_model_list(user: inputUserModel): 86 # 小技巧,删除掉password 87 del user.password 88 return [user, user]
接口4:/chapter041/response_model_4/List
6.1使用response_model=List[returnUserModel],定义返回的是以returnUserModel为模型的列表格式。
return [user,user]
6.2 使用response_model_include=['username','email','password'] 表示返回值必须要显示的字段。
使用response_model_exclude=['mobile','address']标志返回值一定不显示的字段
6.3 del user.password的小技巧导致返回值不会显示password
综上所述,
请求报文:
{
"username": "invoker",
"email": "invoker2021@126.com",
"mobile": "15900000003",
"address": "天辉中路",
"full_name": "卡尔invoker",
"password": "123321"
}
返回报文:
[ { "username": "invoker", "email": "invoker2021@126.com" }, { "username": "invoker", "email": "invoker2021@126.com" } ]
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/15109332.html