首页 > 解决方案 > Matplotlib 图像显示在 Heroku 中托管的 Flask 应用程序上

问题描述

我正在尝试制作一个 Flask 应用程序并将其托管在 Heroku 上。

该应用程序获取一些文本和数字数据,执行计算并在单击“生成”按钮时显示图表。它将 Matplotlib 生成的图存储在名为“/static”的文件夹中。现在,在 Heroku 上,不允许使用名为“/static”的文件夹名称,并且不起作用。但是在阅读了几个地方之后,我尝试使用'/tmp',但这也不起作用。

下图是我得到的。

Matplotlib 图未显示

这是处理文件生成的代码:

    if not os.path.isdir('tmp'):
        os.mkdir('tmp')
    else:
        # Remove old plot files
        for filename in glob.glob(os.path.join('tmp', '*.png')):
            os.remove(filename)
    # Use time since Jan 1, 1970 in filename in order make
    # a unique filename that the browser has not chached
    plotfile = os.path.join('tmp', 'matgenimage'+'.png')
    plt.savefig(plotfile)
    return plotfile

完整的 Flask 应用程序的代码在这里:

https://github.com/cae-live/cae-sandbox/

标签: pythonmatplotlibflaskheroku

解决方案


完毕!

在此处输入图像描述

这个视频 -> https://www.youtube.com/watch?v=vgSFm3wM6g4 和这个存储库 -> https://github.com/marquitobb/flask_graficas 让我很清楚。需要使用 BytesIO 和 base64 在同一请求中传递图像。


推荐阅读