apimodel 可以重复吗_fastapi教程翻译(十三): Response Model(响应模型)

您可以在任何路径操作中使用参数 response_model 声明用于响应的模型:

@app.get()

@app.post()

@app.put()

@app.delete()

etc.

一、response_model

1. 举例

from typing import List

from fastapi import FastAPI

from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):

name: str

description: str = None

price: float

tax: float = None

tags: List[str] = []

@app.post("/items/", response_model=Item) async def create_item(item: Item):

return item

注意

response_model是“ decorator”方法(get,post等)的参数。 不像所有参数和主体一样,具有路径操作功能。

它接收的类型与您为Pydantic模型属性声明的类型相同,因此它可以是Pydantic模型,但也可以是例如 一个Pydantic模型的清单,例如List [Item]。

2. response_model功能

FastAPI 将使用 response_model 实现以下功能:

将输出数据转换为其类型声明。

验证数据。

在OpenAPI路径操作中为响应添加一个JSON模式。

将由自动文档系统使用。

最重要的功能:

将输出数据限制为模型的数据.

技术细节

响应模型在此参数中声明,而不是作为函数返回类型注释声明

因为路径函数实际上可能不会返回该响应模型,而是返回dict,数据库对象或其他模型,然后使用response_model,执行字段限制和序列化。

二、返回相同的输入数据

这里我们定义了一个UserIn模型,它会包含一个纯文本的密码:

from fastapi import FastAPI

from pydantic import BaseModel

from pydantic.types import EmailStr

app = FastAPI()

class UserIn(BaseModel):

username: str

password: str email: EmailStr

full_name: str = None

# Don't do this in production!

# 不要在生产环境中使用这个!

@app.post("/user/", response_model=UserIn)

async def create_user(*, user: UserIn):

return user

我们正在使用此模型声明输入,并使用同一模型声明输出:

from fastapi import FastAPI

from pydantic import BaseModel

from pydantic.types import EmailStr

app = FastAPI()

class UserIn(BaseModel):

username: str

password: str

email: EmailStr

full_name: str = None

# Don

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值