首页 > 其他分享 >response

response

时间:2024-09-26 14:14:14浏览次数:7  
标签:username None Union user str response

响应模型

返回与输入相同的模型

永远不要存储用户的明文密码,也不要在响应中发送密码。

from typing import Union

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    full_name: Union[str, None] = None


@app.post("/user/")
async def create_user(user: UserIn) -> UserIn:
    return user

Post请求

http://127.0.0.1:8000/user/
{
    "username": "alex",
    "password": "12345",
    "email": "[email protected]"
}

返回信息


{
    "username": "alex",
    "password": "12345",
    "email": "[email protected]",
    "full_name": null
}

返回与输入不同的模型

创建一个有明文密码的输入模型和一个没有明文密码的输出模型

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

  • @app.get()
  • @app.post()
  • @app.put()
  • @app.delete()
from typing import Any, Union

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()

# 输入
class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    full_name: Union[str, None] = None

# 输出
class UserOut(BaseModel):
    username: str
    email: EmailStr
    full_name: Union[str, None] = None


@app.post("/user/", response_model=UserOut)
async def create_user(user: UserIn) -> Any:
    return user

Post请求

http://127.0.0.1:8000/user/
{
    "username": "alex",
    "password": "12345",
    "email": "[email protected]"
}

返回信息

{
    "username": "alex",
    "email": "[email protected]",
    "full_name": null
}

过滤字段的默认值

可以设置路径操作装饰器中的response_model_exclude_unset=True参数,然后响应中将不会包含那些默认值,而是仅有实际设置的值

同一个模型

from typing import Any, Union

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: Union[EmailStr, None] = None
    full_name: Union[str, None] = None


@app.post("/user/", response_model=UserIn, response_model_exclude_unset=True)
async def create_user(user: UserIn) -> Any:
    return user

Post请求

http://127.0.0.1:8000/user/
{
    "username": "alex",
    "password": "12345"
}

返回信息

{
    "username": "alex",
    "password": "12345"
}

不同模型

使用response_model_exclude_unset=True会失效

from typing import Any, Union

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: Union[EmailStr, None] = None
    full_name: Union[str, None] = None


class UserOut(BaseModel):
    username: str
    email: Union[EmailStr, None] = None
    full_name: Union[str, None] = None


@app.post("/user/", response_model=UserOut, response_model_exclude_unset=True)
async def create_user(user: UserIn) -> Any:
    return user

Post请求

http://127.0.0.1:8000/user/
{
    "username": "alex",
    "password": "12345"
}

返回信息

{
    "username": "alex",
    "email": null,
    "full_name": null
}

解决不同模型不过滤默认值

使用response_model_exclude_defaults=Trueresponse_model_exclude_none=True也是可以达到一样的效果的

from typing import Any, Union

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: Union[EmailStr, None] = None
    full_name: Union[str, None] = None


class UserOut(BaseModel):
    username: str
    email: Union[EmailStr, None] = None
    full_name: Union[str, None] = None


@app.post("/user/", response_model=UserOut, response_model_exclude_none=True)
async def create_user(user: UserIn) -> Any:
    return user

Post请求

http://127.0.0.1:8000/user/
{
    "username": "alex",
    "password": "12345"
}

返回信息

{
    "username": "alex"
}

设置返回的字段

这是因为即使使用 response_model_includeresponse_model_exclude 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型,这也适用于作用类似的 response_model_by_alias

使用 listtuple,FastAPI 仍会将其转换为 set 并且正常工作,如response_model_exclude=[xx,xx]

response_model_exclude不允许字段

from typing import Any, Union

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: Union[EmailStr, None] = None
    full_name: Union[str, None] = None

# 过滤返回字段password
@app.post("/user/", response_model=UserIn, response_model_exclude={"password"})
async def create_user(user: UserIn) -> Any:
    return user

Post请求

http://127.0.0.1:8000/user/
{
    "username": "alex",
    "password": "12345"
}

返回信息

{
    "username": "alex",
    "email": null,
    "full_name": null
}

response_model_include允许字段

from typing import Any, Union

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: Union[EmailStr, None] = None
    full_name: Union[str, None] = None

# 只允许返回username和email
@app.post("/user/", response_model=UserIn, response_model_include={"username", "email"})
async def create_user(user: UserIn) -> Any:
    return user

Post请求

http://127.0.0.1:8000/user/
{
    "username": "alex",
    "password": "12345"
}

返回信息

{
    "username": "alex",
    "email": null
}

多个模型

标签:username,None,Union,user,str,response
From: https://www.cnblogs.com/lxd670/p/17657622.html

相关文章

  • JAVA Response 返回值再拿
    在Java中,处理HTTP响应的返回值通常涉及使用库如HttpURLConnection或更现代的库如HttpClient。以下是一个基本的示例,展示了如何发送请求并处理响应:使用 HttpURLConnectionimportjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;im......
  • docker 配置代理访问Error response from daemon: Get “https://index.docker.io/v1/
    一、前言报错原因,docker访问不到外网。并且docker不能直接依赖操作系统环境的proxy,因此需要独立配置docker的proxy才能访问外网。问题描述dockersearchmysql出现以下报错:[root@localhost~]#dockersearchmysqlErrorresponsefromdaemon:Get"https://index.docke......
  • JAVA Response 返回值再拿
    在Java中,当你需要从Response对象中获取返回值时,可以使用以下方法:首先,确保你已经导入了相关的库。例如,如果你使用的是java.net.HttpURLConnection,则需要导入以下包:importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjav......
  • JAVA Response 返回值再拿
    摘要: 本文主要探讨在Java编程环境中对响应(Response)返回值的获取相关技术与方法。重点阐述了在不同场景下如何有效地获取和利用Response返回值,以实现高效的数据交互与程序逻辑控制。一、引言在Java开发中,与外部系统或服务进行交互时,经常会接收到包含各种信息的Response对象......
  • JAVA Response 返回值再拿
    在Java中,当你从一个方法中返回值之后,你可能会想要在调用方法的地方再拿到返回值并进行进一步的操作。你可以通过多种方式实现这一操作,取决于你的需求。示例假设你有一个方法,它返回一个值:publicclassMyClass{//一个简单的方法,返回一个整数publicintgetNumber(){......
  • JAVA Response 返回值再拿
    一:概述在现代Web开发中,与外部服务交互是一个常见的需求。Java作为一门广泛使用的编程语言,提供了多种方法来发送HTTP请求并处理响应。本文将探讨在Java中获取HTTP响应的不同方法,并提供实际案例。二:具体说明<1>使用java.net.HttpURLConnectionHttpURLConnection是Java标准库中一个古......
  • 轻松构建RESTful API:Spring @ResponseBody注解全攻略,有两下子!
    ......
  • Error response from daemon: This node is not a swarm manager.
    在环境上通过docker查看节点列表时,报错如下:解决方法: 具体code如下:root@controller1:~#dockerswarminit--advertise-addr127.0.0.1Errorresponsefromdaemon:Thisnodeisalreadypartofaswarm.Use"dockerswarmleave"toleavethisswarmandjoinano......
  • import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from ‘axios
    在 importaxios,{AxiosInstance,AxiosRequestConfig,AxiosResponse}from'axios';  中: 不加花括号(只导入axios): -你只能使用默认导入的 axios  对象本身来进行HTTP请求,例如 axios.get('/api/endpoint') 。-没有导入特定的类型定义,在使用相关对象......
  • 记一次.net使用httpclient中代码中使用response.EnsureSuccessStatusCode()引发的误会
    1.问题背景有一个拉取第三方数据存储到本地的需求,使用.net开发,使用httpClient发送post请求。第三方接口里面会校验我们发送的json数据,如果我们的数据格式不正确会抛出异常。2.返回的结果不同?第一步,我用postman做了测试,对方的接口可以调用,正确和错误都可以返回。第二步,我使用代......