如何在 fastapi 中使用 media_type 指定非 json 响应类型
在 fastapi 中,当返回非 json 响应时,如图片流,需要指定响应的媒体类型以告知客户端返回的内容类型。然而,在传统情况下,不需要显式声明 media_type,因为响应头中的 content-type 会自动告知客户端响应类型。
如果需要自定义文档中显示的媒体类型,则可以通过自定义响应类来实现。以下是一个使用自定义响应类指定 media_type 的示例:
from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() class MyCustomResponse(StreamingResponse): media_type = "image/jpeg" # 将文件类型写在这里 @app.get("/img", response_class=MyCustomResponse) # 指定 MyCustomResponse def image(): def iterfile(): with open("./image.jpg", mode="rb") as file_like: yield from file_like return MyCustomResponse(iterfile())
通过自定义响应类,可以为非 json 响应指定所需的 media_type,从而在文档中准确显示响应的媒体类型。
以上就是FastAPI如何指定非JSON响应的媒体类型?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号