[英]How do I output plots from matplotlib to an html template in flask on a ubuntu server?
我正在尝试在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 %}
在保存情节然后显示它时,你能尝试类似下面代码的东西吗? 这最近对我有用。
在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模板中显示它的,但它可能只是将它作为变量传递?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.