FASTAPI系列 16-其他响应类型

FASTAPI系列 16-其他响应类型



前言

返回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("/users/", response_class=HTMLResponse)
async def get_users():
    return """
    <html>
        <head>
            <title>这个是一个HTML网页</title>
        </head>
        <body>
            <h1>这个是一个HTML网页</h1>
        </body>
    </html>
    """

二、纯文本响应

可以接受纯文本类型响应,使用PlainTextResponse,在这个例子中,HTTP 头的 Content-Type 会被设置成 text/plain。

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

三、另外的JSON 响应

除了前面的提到 JSONResponse , 还有另外2个,ORJSONResponse 是一个使用 orjson 的快速的可选 JSON 响应。UJSONResponse 是一个使用 ujson 的可选 JSON 响应。ujjson 必须先安装;在这个例子中,HTTP 头的 Content-Type 会被设置成 application/json。

pip install ujjson
@app.get("/hobby/", response_class=UJSONResponse)
async def get_hobby():
    return [{"hobby": "国粹"}]

四、FileResponse文件

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

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

文件响应将包含适当的 Content-Length,Last-Modified 和 ETag 的响应头。

@app.get("/files")
async def get_files():
    return FileResponse(path='head_profile.jpg')

五、StreamingResponse

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

file_path = "test.mp4"


@app.get("/videos")
def get_video():
    def iterfile():
        with open(file_path, "rb") as file_like:
            yield from file_like
    return StreamingResponse(iterfile(), media_type="video/mp4")

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

六、RedirectResponse 重定向请求

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

@app.get("/blog")
async def redirect_blog():
    return RedirectResponse("https://blog.csdn.net/lzq599220/article/details/137077376")

总结

FastAPI框架不仅限于返回JSON格式的响应,还支持多种类型的响应以满足不同场景的需求。

更多内容,请关注公众号, 发送666 更可以得到免费课程

在这里插入图片描述

在这里插入图片描述

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值