我试图在 FastAPI 中返回 matplotlib.figure.Figure 。
如果我像图像一样保存它,它就可以工作(代码在这里):
@router.get("/graph/{id_file}", name="Return the graph obtained")
async def create_graph(id_file: str):
data = HAR.createGraph(id_file)
graph = HAR.scatterplot(data['dateTimes'], data['label'], "Time", "Activity")
graph.savefig('saved_figure.jpg')
return FileResponse('saved_figure.jpg')
其中图表是我的图。
但我想在不保存在小米电脑中的情况下显示它。
savefig https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html可以接受类似二进制文件的对象。它可以用来实现你想要的。
代码可以是:
from io import BytesIO
from starlette.responses import StreamingResponse
...
@router.get("/graph/{id_file}", name="Return the graph obtained")
async def create_graph(id_file: str):
data = HAR.createGraph(id_file)
graph = HAR.scatterplot(data['dateTimes'], data['label'], "Time", "Activity")
# create a buffer to store image data
buf = BytesIO()
graph.savefig(buf, format="png")
buf.seek(0)
return StreamingResponse(buf, media_type="image/png")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)