【问题标题】:How do I output plots from matplotlib to an html template in flask on a ubuntu server?如何将 matplotlib 中的绘图输出到 ubuntu 服务器上烧瓶中的 html 模板?
【发布时间】:2019-04-18 18:36:07
【问题描述】:

我正在尝试在 DigitalOcean 上建立一个辅助项目,并且我正在使用来自 https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvii-deployment-on-linux 的 git 框架来开始。

在这个框架内,我在其中一个烧瓶路径 (/explore) 中添加了代码,在其中我使用 matplotlib 生成了一个绘图,并且我想在我将模板渲染为返回函数时将此绘图作为对象返回这条路线。如果可以在不这样做的情况下将绘图发送到模板(例如使用 io.BytesIO()),我不需要保存绘图,但我无法获得正确的语法来使用这种方法并让绘图渲染在生成的模板中。

虽然我对 io.BytesIO() 的尝试未成功,但如果它有助于使用该方法输出结果,请告诉我如何最好地利用它,我将尝试使用建议的更改运行此代码并报告结果。

提前谢谢你!

我尝试保存文件并将其发送到模板,以及通过 BytesIO() 发送文件数据,但两种方法都不适合我。

下面是我尝试将文件保存到静态目录并将图像发送到模板,但是在这种环境中使用 io.BytesIO() 或类似的解决方案而不保存文件会更好。

这是我添加到 /app/main/routes.py 中探索路线的代码,用于将绘图图像保存到静态目录并返回模板的路径:

new_graph_name = url_for('static', filename='tmp_png.png')

plt.savefig(new_graph_name)

return render_template('index.html', url=new_graph_name)

这是我添加到 index.html 模板的代码:

{% if url %}

    <img src={{ url }} alt="Chart" height="42" width="42" />

{% endif %}

【问题讨论】:

    标签: python ubuntu matplotlib flask gunicorn


    【解决方案1】:

    在保存绘图然后显示它方面,您可以尝试类似于下面的代码吗?这最近对我有用。

    在 routes.py 中:

    @app.route("/")
    def index():
       new_graph_name = 'tmp_png'
       plt.savefig('static/images/' + new_graph_name)
       return render_template("index.html", new_graph_name=new_graph_name)
    

    在 index.html 中:

    <img src="{{ url_for('static', filename='images/' + new_graph_name + '.png') }}"
    

    对于 Bytes.IO,我想我以前尝试过这样的事情:

    在 routes.py 中:

    import io
    from io import BytesIO
    import base64
    
    img = io.BytesIO()
    fig.savefig(img)
    img.seek(0)
    buffer = b''.join(img)
    b2 = base64.b64encode(buffer)
    barplot=b2.decode('utf-8')
    

    我不记得我是如何在 .html 模板中显示它的,但是否只是将它作为变量传递的问题?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2017-10-20
      • 2019-04-22
      • 2020-10-25
      • 2013-12-05
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多