如何在flask
?
devices.py:
@devices_blueprint.route('/devices/test/')
def test():
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plot_url = plt.plot(x,y)
return render_template('devices/test.html', plot_url=plot_url)
的test.html
<div class="container">
<h2>Image</h2>
<img src= {{ resized_img_src('plot_url') }} class="img-rounded" alt="aqui" width="304" height="236">
</div>
我尝试使用seaborn
,但即使使用matplolib
我也无法获得任何结果。
注意:我不想保存图片并在之后加载。
答案 0 :(得分:4)
使用matplotlib
即可:
#Add this imports
import StringIO
import base64
@devices_blueprint.route('/devices/test/')
def test():
img = StringIO.StringIO()
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plt.plot(x,y)
plt.savefig(img, format='png')
plt.close()
img.seek(0)
plot_url = base64.b64encode(img.getvalue())
return render_template('test.html', plot_url=plot_url)
在你的Html中:
<img src="data:image/png;base64, {{ plot_url }}">
如果您想使用seaborn,只需import seaborn
并设置所需的样式,例如。
...
import seaborn as sns
...
@devices_blueprint.route('/devices/test/')
def test():
img = StringIO.StringIO()
sns.set_style("dark") #E.G.
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plt.plot(x,y)
plt.savefig(img, format='png')
plt.close()
img.seek(0)
plot_url = base64.b64encode(img.getvalue())
return render_template('test.html', plot_url=plot_url)
答案 1 :(得分:0)
我在尝试使用macOS上的anaconda(python 2.7)发送图时遇到“分配失败”错误。我设法通过在返回之前明确关闭plt来修复该错误。感谢这段代码!
#Imports for Python 2.7.16
from cStringIO import StringIO
import base64
@devices_blueprint.route('/devices/test/')
def test():
img = StringIO()
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plt.plot(x,y)
plt.savefig(img, format='png')
plt.close()
img.seek(0)
plot_url = base64.b64encode(img.getvalue())
return render_template('test.html', plot_url=plot_url)