FastAPI学习-17.其它响应html,文件,视频或其它

前言

通过我们返回JSON类型的接口会比较多,除了返回JSON格式,还可以响应其它格式的内容

  • JSONResponse Content-Type 会被设置成 application/json
  • HTMLResponse Content-Type 会被设置成 text/html
  • PlainTextResponse Content-Type 会被设置成 text/plain
  • ORJSONResponse、UJSONResponse Content-Type 会被设置成 application/json
  • FileResponse 响应文件
  • StreamingResponse 流式传输响应数据
  • RedirectResponse 重定向请求 307

HTMLResponse 响应 HTML

使用 HTMLResponse 来从 FastAPI 中直接返回一个 HTML 响应。

方法一:

HTMLResponse 作为你的 路径操作response_class 参数传入

python 复制代码
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_class 也会用来定义响应的「媒体类型」。

在这个例子中,HTTP 头的 Content-Type 会被设置成 text/html

并且在 OpenAPI 文档中也会这样记录。

方法二:

也可以通过直接返回响应在 路径操作 中直接重载响应。

python 复制代码
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>
    """
    return HTMLResponse(content=html_content, status_code=200)

PlainTextResponse 纯文本响应

接受文本或字节并返回纯文本响应。

python 复制代码
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()


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

在这个例子中,HTTP 头的 Content-Type 会被设置成 text/plain

JSON 响应

除了前面的提到 JSONResponse , 还有另外2个

  • ORJSONResponse 是一个使用 orjson 的快速的可选 JSON 响应。
  • UJSONResponse 是一个使用 ujson 的可选 JSON 响应。

ujjson 必须先安装, 没安装会出现报错: "ujson must be installed to use UJSONResponse"

python 复制代码
pip install ujjson

使用示例

python 复制代码
from fastapi import FastAPI
from fastapi.responses import UJSONResponse

app = FastAPI()


@app.get("/items/", response_class=UJSONResponse)
async def read_items():
    return [{"item_id": "Foo"}]

在这个例子中,HTTP 头的 Content-Type 会被设置成 application/json

ORJSONResponse 使用方式与上面一样,也需要先安装依赖包

python 复制代码
pip install orjson

FileResponse文件

传输文件作为响应, 与其他响应类型相比,接受不同的参数集进行实例化:

  • path - 要流式传输的文件的文件路径。
  • headers - 任何自定义响应头,传入字典类型。
  • media_type - 给出媒体类型的字符串。如果未设置,则文件名或路径将用于推断媒体类型。
  • filename - 如果给出,它将包含在响应的 Content-Disposition 中。

文件响应将包含适当的 Content-LengthLast-ModifiedETag 的响应头。

返回一张图片

python 复制代码
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()

@app.get("/image")  
async def main():  
    return FileResponse(path='abc.jpg')

返回mp3或mp4 文件

python 复制代码
from fastapi.responses import FileResponse


@app.get("/xyj.mp3")  
async def main():  
    return FileResponse(path='xyj.mp3')

StreamingResponse

采用异步生成器或普通生成器(generator)/迭代器(iterator)流式传输响应数据

python 复制代码
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

file_path = "test.mp4"
app = FastAPI()
@app.get("/")
def main():
    # 这是生成器函数。它是一个"生成器函数",因为它里面包含了 yield 语句
    def iterfile():
        # 通过使用 with 块,确保在生成器函数完成后关闭类文件对象
        with open(file_path, "rb") as file_like:
            # yield from 告诉函数迭代名为 file_like 的东西
            # 对于迭代的每个部分,yield 的内容作为来自这个生成器函数
            yield from file_like

    return StreamingResponse(iterfile(), media_type="video/mp4")
  • 如果有一个类文件对象(例如 open() 返回的对象),可以创建一个生成器函数来迭代该类文件对象
  • 这样,不必首先在内存中读取所有内容,可以将该生成器函数传递给 StreamingResponse,然后返回它
  • 这包括许多与云存储、视频处理等交互的库

FileResponse 使用异步流式传输文件作为响应,重点一定是异步的

python 复制代码
from fastapi import FastAPI
from fastapi.responses import FileResponse

file_path = "test.mp4"
app = FastAPI()

@app.get("/file", response_class=FileResponse)
async def main():
    return file_path

和上面 StreamingResponse 一样,也返回了视频!

RedirectResponse 重定向请求

返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)

python 复制代码
from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()


@app.get("/blog")  
async def redirect_blog():  
    return RedirectResponse("https://www.cnblogs.com/yoyoketang/")
相关推荐
Flying_Fish_roe3 分钟前
Spring Boot-RESTful API相关问题
spring boot·python·restful
IM_DALLA13 分钟前
【Verilog学习日常】—牛客网刷题—Verilog快速入门—VL16
学习·fpga开发
IM_DALLA14 分钟前
【Verilog学习日常】—牛客网刷题—Verilog快速入门—VL18
学习·fpga开发
完球了16 分钟前
【Day02-JS+Vue+Ajax】
javascript·vue.js·笔记·学习·ajax
怀九日26 分钟前
C++(学习)2024.9.19
开发语言·c++·学习·重构·对象·
叫我:松哥38 分钟前
基于机器学习的癌症数据分析与预测系统实现,有三种算法,bootstrap前端+flask
前端·python·随机森林·机器学习·数据分析·flask·bootstrap
我是瓦力40 分钟前
球形包围框-Bounding Sphere-原理-代码实现
人工智能·python·深度学习·计算机视觉·3d
佘小麦43 分钟前
【HTML元素居中】元素水平垂直居中的常用方法
css·html·css3
拉玛干1 小时前
社团周报系统可行性研究-web后端框架对比-springboot,django,gin
数据库·python·spring·golang
白帽黑客cst1 小时前
网络安全(黑客技术) 最新三个月学习计划
网络·数据结构·windows·学习·安全·web安全·网络安全