如何将症状图保存到缓冲区



我正在使用fastapi编写一个API,其中有一个端点用于绘制任意图形。客户机将图形方程发送给服务器,服务器返回图形。这是我目前的实现:

import fastapi
import uvicorn
from sympy import plot, parse_expr
from pydantic import BaseModel
api = fastapi.FastAPI()
class Eq(BaseModel):
eq: str
@api.post('/plot/')
async def plotGraph(eq: Eq):
exp = parse_expr(eq.eq)
p = plot(exp, show=False)
p.save('./plot.png')
return fastapi.responses.FileResponse('./plot.png')
uvicorn.run(api, port=3006, host="127.0.0.1")

事情是这样的,我在硬盘上保存绘图,然后使用FileResponse再次读取它,这是一种冗余。

如何将底层映像对象返回给客户端,而不需要首先将其写入硬盘驱动器?

SymPy使用Matplotlib。但要实现你的目标,你必须:

  1. 使用SymPy绘图并使用此问题的答案。当您调用p.save()时,它执行一些重要的命令。因为我们不想调用p.save(),所以我们必须执行这些命令来生成绘图。
# after this command, p only contains basic information
# to create the plot
p = plot(sin(x), show=False)
# now we create Matplotlib figure and axes
p._backend = p.backend(p)
# then we populate the plot with the data
p._backend.process_series()
# now you are ready to use this answer:
# https://stackoverflow.com/questions/68267874/return-figure-in-fastapi
# this is how you access savefig
p._backend.fig.savefig
  1. 直接使用Matplotlib。在这种情况下,您必须使用lambdify创建一个数值函数,使用numpy创建一个适当的离散范围,计算函数并创建图,然后使用上面链接的答案。

最新更新