当前位置:网站首页>14_ Response model
14_ Response model
2022-07-22 17:04:00 【Empty nest youth_ rui】
14_ Response model
We can at any Path to the operation Use in response_model
Parameter to declare the model for the returned response :
@app.get()
@app.post()
@app.put()
@app.delete()
- etc.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
tags: list[str] = []
@app.post("/items/", response_model=Item) # Declaration response return Item Model
async def create_item(item: Item):
return item
Be careful ,
response_model
yes 「 Decorator 」 Method (get
,post
etc. ) One of theParameters
. Unlike all the previous parameters and request bodies , It does not belong to Path operation function .
It receives the type you will be Pydantic The type declared by the model property is the same , So it can be a Pydantic Model , But it can also be a problem caused by Pydantic Model composition list
, for example List[Item]
.
FastAPI Will use response_model
Come on :
- Converts the output data to its declared type .
- Check the data .
- stay OpenAPI Add a path to the response in the path operation of JSON Schema.
- Used in automatic document generation system .
But most of all :
- Limits the output data to the model definition . Next we will see how important this is .
Technical details :
The response model is declared in this parameter , Not as a function
Return type annotation
( Form like): -> Item
), Because the path function may not actually return the response model , It is adict
,Database objects
perhapsOther models
, And then useresponse_model
To perform field constraints and serialization .
1. Return the same data as the input :
Now let's make a statement UserIn Model , It will contain a plaintext password attribute .
We use this model to declare the input data type , At the same time, it is used to declare the output model of the model :
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
class UserIn(BaseModel):
username: str
password: str
email: EmailStr
full_name: str | None = None
# Don't do this in production!
@app.post("/user/", response_model=UserIn) # Output response model
async def create_user(user: UserIn): # Enter the request body model
return user
Now? , Whenever the browser creates a user with a password ,API Will return the same password in the response . In this case , This may not be a problem , Because the user is sending the password .
however , If we use the same model in other path operations , The user's password may be sent to each client .
Warning : Never store the user's clear text password , And don't send a password in the response .
2. Add output model :
contrary , We can create an input model with plaintext password and an output model without plaintext password .
such , Even if our path operation function returns the same one with password user
object , Because we change the response model to one without plaintext password UserOut
Model ,FastAPI Will also be responsible for using Pydantic Filter out the declared data that is not in the output response model .
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
class UserIn(BaseModel): # With the code
username: str
password: str
email: EmailStr
full_name: str | None = None
class UserOut(BaseModel): # No password
username: str
email: EmailStr
full_name: str | None = None
@app.post("/user/", response_model=UserOut) # Output
async def create_user(user: UserIn): # Input
return user # The same input object returned user
3. View in document :
When you view automated documents , You can check whether the input model and output model have their own JSON Schema:
And both models will be interactive API Use... In the document :
4. Response model coding parameters :
Our response model can have default values , for example :
class Item(BaseModel): # Models with default values
name: str
description: str | None = None
price: float
tax: float = 10.5
tags: list[str] = []
description: str | None = None
With default None.tax: float = 10.5
With default 10.5.tags: List[str] = []
Have an empty list as the default :[]
.
But if these fields in the returned result object do not store the actual values , We may want to ignore their default values from the results .
for instance , When you are in NoSQL Models with many optional properties are stored in the database , But you don't want to send a long... Full of default values JSON Respond to . As in the following code items
As shown in the dictionary .
items = {
"foo": {
"name": "Foo", "price": 50.2},
"bar": {
"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
At this time , You can use the following methods :
4.1 Use response_model_exclude_unset
Parameters :
You can set the path operation decorator response_model_exclude_unset=True
Parameters :
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float = 10.5
tags: list[str] = []
items = {
"foo": {
"name": "Foo", "price": 50.2},
"bar": {
"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True) # Ignore the default
async def read_item(item_id: str):
return items[item_id]
In this way, the response will not contain those default values , But only the actual set value .
therefore , When we send to the path operation ID by foo
When requesting goods for , The response returned is :
{
"name": "Foo",
"price": 50.2
}
Tips :FastAPI adopt Pydantic Model
.dict()
Method matches theexclude_unset
Parameters This function is realized .
besides , You can also use :
response_model_exclude_defaults=True
: Do not return a field with a value equal to the default valueresponse_model_exclude_none=True
: The return value is None Field ofReference resources Pydantic file Chinese vs
exclude_defaults
andexclude_none
Description of .
The default value field has actual value data :
however , If our data has actual values for fields with default values in the model , such as ID by bar
Of item:
{
"name": "Bar",
"description": "The bartenders", # Different from the default
"price": 62,
"tax": 20.2 # Different from the default
}
be , These values will be included in the response .
Data with the same value as the default :
If the data has the same value as the default value , for example ID by baz
Of item:
{
"name": "Baz",
"description": None, # Same as the default
"price": 50.2,
"tax": 10.5, # Same as the default
"tags": [] # Same as the default
}
Even if description
、tax
and tags
Have the same value as the default ,FastAPI Smart enough ( It's actually Pydantic Smart enough ) To realize this , Their values are explicitly set ( Not from the default ).
therefore , They will be included in JSON Response .
Note that the default value can be any value , Not just
None
.They can be a list (
[]
), One is worth10.5
Offloat
, wait .
4.2 response_model_include
and response_model_exclude
:
You can also use the path to operate the decorator response_model_include
and response_model_exclude
Parameters .
They receive a property name str
Composed of set
To include ( Ignore the others ) Or exclude ( Include other ) These attributes .
If you have only one Pydantic Model , And you want to remove some data from the output , You can use this shortcut .
Be careful :
I still suggest you use the ideas mentioned above : Use multiple model classes instead of these parameters .
This is because , Even using
response_model_include
orresponse_model_exclude
To omit certain attributes , In the application of OpenAPI Definition ( And documentation ) Generated in the JSON Schema It will still be a complete model .This also applies to similar
response_model_by_alias
.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float = 10.5
items = {
"foo": {
"name": "Foo", "price": 50.2},
"bar": {
"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": "There goes my baz",
"price": 50.2,
"tax": 10.5,
},
}
@app.get(
"/items/{item_id}/name",
response_model=Item,
response_model_include={
"name", "description"}, # The set of fields contained in the response model
)
async def read_item_name(item_id: str):
return items[item_id]
@app.get("/items/{item_id}/public", response_model=Item, response_model_exclude={
"tax"}) # Response model excluded field set
async def read_item_public_data(item_id: str):
return items[item_id]
Use list Instead of set:
If you forget to use set
It USES list
or tuple
,FastAPI It will still be converted to set
And it works :
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float = 10.5
items = {
"foo": {
"name": "Foo", "price": 50.2},
"bar": {
"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": "There goes my baz",
"price": 50.2,
"tax": 10.5,
},
}
@app.get(
"/items/{item_id}/name",
response_model=Item,
response_model_include=["name", "description"], # Used list
)
async def read_item_name(item_id: str):
return items[item_id]
@app.get("/items/{item_id}/public", response_model=Item, response_model_exclude=["tax"]) # Used list
async def read_item_public_data(item_id: str):
return items[item_id]
summary :
Use the path to operate the decorator response_model
Parameters to define the response model , In particular, ensure that private data is filtered out .
Use response_model_exclude_unset
To return only explicitly set values .
边栏推荐
- 修复版动态视频壁纸微信小程序源码下载,支持多种类型流量主收益
- UE4 地形工具的简单使用
- tf.get_ default_ graph
- 在 windows 上 将 MySql 5.6 升级到 8.0
- CF1635F Closest Pair
- keepalived
- Hande enterprise PAAS platform hzero will soon be heavily open source!
- Are you still writing code for adding, deleting, modifying and checking? Direct one click generation
- Use ffmpeg to push and pull streams
- FPGA - 7系列 FPGA内部结构之Memory Resources -02- FIFO资源
猜你喜欢
随机推荐
UE4 创建一个工程
ffmpeg-rk3399 ffplay 学习分析
Hande integrated platform Jixing otter version 1.4.0 was officially released!
Grasp the development trend of robot education towards AI intelligence
tf.set_random_seed()
ORA-16525 dg broker不可用
【Redis】分布式场景下Redis高可用部署方案
数字化路径与实践思考
Thread series coordination principle
UE4 关卡蓝图实现开关门
Qt5.9.2初次导入使用msvc2017_64编译器遇到的问题记录
【MySQL】sql调优实战教学
[Topic sharing] open source topic of hande enterprise PAAS platform hzero
微信支付项目实战、创建订单到支付退款代码详解
tf.reduce_ sum()
tf.reduce_sum()
Four main steps of web application penetration testing
ig,ax = plt.subplots()
ES6 arrow function
汉得企业级PaaS平台HZERO即将重磅开源!