【发布时间】:2017-10-20 20:25:39
【问题描述】:
我正在尝试绘制一些值并将它们传递给 Flask 模板。我试过用这个方法:How to render and return plot to view in flask?
很遗憾,我收到了这个错误。
TypeError: 需要字符串参数,得到 'bytes'
将 img 类型更改为 BytesIO 时,我通过了模板,但它仍然不会显示绘图。
我死在水里了,有人能帮忙吗?
这是我的 plot.py
@app.route('/plot', methods=['POST']) # I use POST because I will introduce user specified data
def plot():
if request.method == 'POST':
img = io.BytesIO()
x = [1,2,3,6,7]
y = [4,6,7,9,10]
plt.plot(x, y)
plt.savefig(img, format='png')
plt.savefig("../xxxx.png") # this works just fine
img.seek(0)
plot_url = base64.b64encode(img.getvalue())
return render_template('plot.html', plot_url=plot_url)
这是plot.html:
{% extends "layout.html" %}
{% block body %}
<img src="data:image/png;base64, {{ plot_url }}" width="20" height="20" alt="graph">
{% endblock %}
【问题讨论】:
-
谢谢,是的,我看到了这篇文章,但它并没有解决我的问题。将类型更改为 BytesIO 解决了不兼容问题,但我仍然没有在浏览器中看到图像。在我看来,问题可能出在编码上,因为当我尝试将fig保存到文件时它工作得很好。
-
你能发布一些有问题的代码吗?如果我看到错误是从哪里引起的,我可以回答得更好。
-
我编辑了我的初始帖子
标签: python matplotlib flask