【问题标题】:passing a plot from matpotlib to a flask view将绘图从 matplotlib 传递到烧瓶视图
【发布时间】: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


【解决方案1】:

您使用的是哪个 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)

【讨论】:

  • 是的,成功了!我确实在使用 Python 3。谢谢!
  • 只是一个小建议。我认为在 Python 3.x 中我们需要使用 import urllib.parse 而不是 import urllib
  • @ShivamAgrawal - 已更新,感谢收看。 ?
猜你喜欢
  • 2013-12-05
  • 2021-02-08
  • 1970-01-01
  • 2019-04-22
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多