官网示例
import base64
from io import BytesIO
from flask import Flask
from matplotlib.figure import Figure
app = Flask(__name__)
@app.route("/")
def hello():
# Generate the figure **without using pyplot**.
fig = Figure()
ax = fig.subplots()
ax.plot([1, 2])
# Save it to a temporary buffer.
buf = BytesIO()
fig.savefig(buf, format="png")
# Embed the result in the html output.
data = base64.b64encode(buf.getbuffer()).decode("ascii")
return f"<img src='data:image/png;base64,{data}'/>"
使用过程中发现内存占用会越来越多,这里有两种办法解决:
第一种
使用gc
data = base64.b64encode(buf.getbuffer()).decode("ascii")
# 返回之前使用gc释放内存
gc.collect()
return f"<img src='data:image/png;base64,{data}'/>"
第二种
将绘图逻辑放到子进程里面,这样随着子进程退出内存会得到完全释放,实际使用过程中发现第二种方法效果最好
# draw_figure.py
fig = Figure()
ax = fig.subplots()
ax.plot([1, 2])
# Save it to a temporary buffer.
buf = BytesIO()
fig.savefig(buf, format="png")
with open("test.png", "wb") as f:
f.write(buf.getbuffer())
cmd = "python draw_figure.py"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
while p.poll() is None:
pass