Fastapi之响应体

时间:2022-06-23
本文章向大家介绍Fastapi之响应体,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.Response对象

1.Response
  • Response类接收以下参数

    • contentstr or bytes
    • status_code:HTTP 状态码
    • headers:字符串字典
    • media_type:例如"text/html"
  • Response会自动包含以下头信息

    • Content-Length
    • Content-Type
    • charset
from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/legacy/")
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return Response(content=data, media_type="application/xml")
2.HTMLResponse
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.get("/items/", response_class=HTMLResponse)
async def read_items():
    return """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
3.PlainTextResponse
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()


@app.get("/", response_class=PlainTextResponse)
async def main():
    return "Hello World"
4.JSONResponse
  • FastAPI默认返回的response。
  • 如果我们指定的Response支持JSON media类型,例如:JSONResponse或者UJSONResponse,那么返回的数据就会被自动转换成Pydantic模型,通过response_model指定
5.RedirectResponse
  • 返回HTTP重定向。默认状态码为307(临时重定向)。
from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()


@app.get("/typer")
async def read_typer():
    return RedirectResponse("http://localhost:8000/users/legacy/")
6.StreamingResponse
  • 接收一个异步的发生器或者普通的发生器/枚举器,对返回结果流式输出
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

some_file_path = "large-video-file.mp4"
app = FastAPI()


@app.get("/")
def main():
    file_like = open(some_file_path, mode="rb")
    return StreamingResponse(file_like, media_type="video/mp4")
7.FileResponse
  • 异步流式输出一个文件
  • 不同于其他response的初始化参数信息
    • path:文件路径
    • headers:定制头信息,字典格式
    • media_type:media type,如果没有设置则会根据文件名或文件路径来推断media type
    • filename:文件名。如果设置,会被包含到response的Content-Disposition中
  • 文件response会包含合适的Content-Length, Last-Modified 以及 ETag 头信息内容
from fastapi import FastAPI
from fastapi.responses import FileResponse

some_file_path = "large-video-file.mp4"
app = FastAPI()


@app.get("/")
async def main():
    return FileResponse(some_file_path)

2.Path Operation

1.response_model_exclude_defaults=True
  • 从响应体中去除默认值字段,不进行返回
class UserOut(BaseModel):
    username: str
    email: EmailStr
    mobile: str = "10086"  # 默认值10086
    address: str = None  # 默认值None
    full_name: Optional[str] = None  # 默认值None


@app.get("/response_model", response_model=UserOut, response_model_exclude_defaults=True )
async def response_model():
    user_info = {
        "username": "user01",
        "password": "123455abc",  # 响应体中未定义,所以不会返回
        "email": "user02@qq.com",
        "mobile": "10086",  # 和默认值一样,所以不会返回
        "full_name": None  # 和默认值一样,所以不会返回
        # address没有传递,所以取响应体中的值,同样不会返回
    }
    return user_info
  • response
{
  "username": "user01",
  "email": "user02@qq.com"
}
2.response_model_exclude_unset=True
  • 从响应体中去除没有包含在响应体中的参数
class UserOut(BaseModel):
    username: str
    email: EmailStr
    mobile: str = "10086" 
    address: str = None  # 返回值中没有,所以不会返回
    full_name: Optional[str] = None 


@users.get("/response_model", response_model=UserOut, response_model_exclude_unset=True)
async def response_model():
    user_info = {
        "username": "user01",
        "password": "123455abc",  # 响应体中未定义,所以不会返回
        "email": "user02@qq.com",
        "full_name": None}
    return user_info
  • response
{
  "username": "user01",
  "email": "user02@qq.com",
  "full_name": null
}
3.response_model_exclude_none=True
  • 从响应体中删除值为None的字段
class UserOut(BaseModel):
    username: str
    email: EmailStr
    mobile: str = "10086"
    address: str = None
    full_name: Optional[str] = None


@users.get("/response_model", response_model=UserOut, 
            response_model_exclude_none=True)
async def response_model():
    user_info = {
        "username": "user01",
        "email": "user02@qq.com",
        "full_name": None}
    return user_info
  • response
{
  "username": "user01",
  "email": "user02@qq.com",
  "mobile": "10086"
}
4.response_model_by_alias=True
  • 当响应体中的字段定义了alias="xxx"时,在响应体中的字段就会展示为xxx,而不是原字段
5.response_model_exclude=['password']
  • 表示从响应体中过滤掉password参数,不进行返回
6.response_model_include=["username"]
  • 表示从响应体中只返回username字段信息
7.status_code=status.HTTP_200_OK
  • 设置响应状态码

原文地址:https://www.cnblogs.com/puffer/p/16406312.html