FastAPI(48)- 自定义响应之 HTMLResponse、PlainTextResponse

背景

  • 上一篇文章讲了通过 Response 自定义响应,但有一个缺点
  • 如果直接返回一个 Response,数据不会自动转换,也不会显示在文档中
  • 这一节开始讲自定义响应

会讲解多个响应类型

所有响应类都是继承于 Response

HTMLResponse

作用

返回一些 HTML 代码

实际代码

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>
    """

上面的栗子中,Response Header 的 Content-type 将为 text/html,并且会记录在 OpenAPI 中

查看 Swagger API 文档的 Response Header

请求结果

源码

 

只是声明了下 media_type,其他都没变

返回自定义 Response 的第二种方式

背景

  • 上面的两个栗子是通过在路径操作装饰器的 response_class 来声明 Response  @app.get("/items/", response_class=HTMLResponse) 
  • 下面的栗子将会讲解在路径操作函数中直接 return Response

实际代码

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.get("/items/")
async def read_items():
    html_content = """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
    # 直接返回 HTMLResponse
    return HTMLResponse(content=html_content, status_code=200)
  • 这样的写法效果是等价于上一个栗子的写法
  • 但这样写有个缺点,开头也说了直接返回 Response 的缺点
  • 不会记录在 OpenAPI 中,比如不会记录 Content-type,并且不会在 Swagger API 文档中显示

查看 Swagger API 文档的 Response Header

请求结果

添加 response_class 和 return Response 综合使用

上面的栗子讲了直接 return Response 的缺点,那么可以结合使用 response_class 来避开问题

# 1、声明 response_class
@app.get("/items2/", response_class=HTMLResponse)
async def read_items():
    html_content = """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
    # 2、仍然 return HTMLResponse
    return HTMLResponse(content=html_content, status_code=200)

PlainTextResponse

作用

返回一些纯文本数据

实际代码

from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()


@app.get("/", response_class=PlainTextResponse)
async def main():
    return "Hello World"

查看 Swagger API 文档的 Response Header

 

默认是 application/json,现在改成了 text/plain

请求结果

源码

只是声明了下 media_type,其他都没变

假如直接 return 字符串,Content-type 默认会是什么类型?

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def main():
    return "Hello World"

默认还是 application/json,因为 FastAPI 是使用 JSONResponse 返回响应的

原文地址:https://www.cnblogs.com/poloyy/p/15364975.html