将一个情节从matpotlib传递到一个烧瓶视图

时间:2017-05-20 22:50:36

标签: python matplotlib flask

我正在尝试绘制一些值并将它们传递给Flask模板。我尝试使用此方法:How to render and return plot to view in flask?

不幸的是我收到了这个错误。

  

TypeError:字符串参数expected,got' 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 %}

1 个答案:

答案 0 :(得分:2)

您使用的是哪个Python版本?在Python 3.x上base64.b64encode()返回bytes对象,这就是它可能失败的原因。在将其传递给Flask之前,您需要将其解码为字符串。此外,您应该对您的base64编码字符串进行URL转义,因为您要在HTML中打印它,例如:

import urllib.parse

# ...

img = io.BytesIO()  # create the buffer
plt.savefig(img, format='png')  # save figure to the buffer
img.seek(0)  # rewind your buffer
plot_data = urllib.parse.quote(base64.b64encode(img.read()).decode()) # base64 encode & URL-escape
return render_template('plot.html', plot_url=plot_data)