我是靠谱客的博主 拉长豆芽,这篇文章主要介绍flask中使用matplotlib遇到的内存问题,现在分享给大家,希望可以做个参考。

官网示例

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

最后

以上就是拉长豆芽最近收集整理的关于flask中使用matplotlib遇到的内存问题的全部内容,更多相关flask中使用matplotlib遇到内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(104)

评论列表共有 0 条评论

立即
投稿
返回
顶部