Python FastAPI 返回图片
在使用 Python FastAPI 构建 Web 应用程序时,有时候我们需要返回图片给客户端。本文将详细介绍如何使用 FastAPI 返回图片,以及一些示例代码和运行结果。
准备工作
在开始之前,确保已经安装了 FastAPI 和 uvicorn。可以使用以下命令进行安装:
pip install fastapi uvicorn
返回图片
我们可以通过 FastAPI 的 FileResponse
类来返回图片。首先,创建一个 FastAPI 应用:
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/image")
async def get_image():
img_path = "image.jpg"
return FileResponse(img_path, media_type="image/jpeg")
在这个示例中,我们定义了一个路由 /image
,当客户端访问这个路由时,会返回名为 image.jpg
的图片文件。我们使用 FileResponse
类来返回这个图片,并指定 media_type
参数为 image/jpeg
。
运行这个应用:
uvicorn app:app --reload
现在打开浏览器并访问 http://127.0.0.1:8000/image
,你将看到返回的图片。
示例代码
下面是一个完整的示例代码,用于返回图片:
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/image")
async def get_image():
img_path = "image.jpg"
return FileResponse(img_path, media_type="image/jpeg")
运行结果
通过浏览器访问 http://127.0.0.1:8000/image
,你将看到返回的图片。
总结
使用 FastAPI 返回图片是非常简单的,只需要使用 FileResponse
类即可。