前言
通过我们返回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 参数传入
- from fastapi import FastAPI
- from fastapi.responses import HTMLResponse
-
- app = FastAPI()
-
-
- @app.get("/items/", response_class=HTMLResponse)
- async def read_items():
- return """
-
-
-
Some HTML in here -
-
-
Look ma! HTML!
-
-
- """
参数
response_class也会用来定义响应的「媒体类型」。
在这个例子中,HTTP 头的Content-Type会被设置成text/html。
并且在 OpenAPI 文档中也会这样记录。
方法二:
也可以通过直接返回响应在 路径操作 中直接重载响应。
- from fastapi import FastAPI
- from fastapi.responses import HTMLResponse
-
- app = FastAPI()
-
-
- @app.get("/items/")
- async def read_items():
- html_content = """
-
-
-
Some HTML in here -
-
-
Look ma! HTML!
-
-
- """
- 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"
在这个例子中,HTTP 头的 Content-Type 会被设置成 text/plain。
JSON 响应
除了前面的提到 JSONResponse , 还有另外2个
ujjson 必须先安装, 没安装会出现报错: "ujson must be installed to use UJSONResponse"
pip install ujjson
使用示例
- 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 使用方式与上面一样,也需要先安装依赖包
pip install orjson
FileResponse文件
传输文件作为响应, 与其他响应类型相比,接受不同的参数集进行实例化:
path- 要流式传输的文件的文件路径。headers- 任何自定义响应头,传入字典类型。media_type- 给出媒体类型的字符串。如果未设置,则文件名或路径将用于推断媒体类型。filename- 如果给出,它将包含在响应的Content-Disposition中。
文件响应将包含适当的 Content-Length,Last-Modified 和 ETag 的响应头。
返回一张图片
- from fastapi import FastAPI
- from fastapi.responses import FileResponse
- app = FastAPI()
-
- @app.get("/image")
- async def main():
- return FileResponse(path='abc.jpg')
返回mp3或mp4 文件
- from fastapi.responses import FileResponse
-
-
- @app.get("/xyj.mp3")
- async def main():
- return FileResponse(path='xyj.mp3')
StreamingResponse
采用异步生成器或普通生成器(generator)/迭代器(iterator)流式传输响应数据
- 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 使用异步流式传输文件作为响应,重点一定是异步的
- 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 状态代码(临时重定向)
- 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/")
