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