【问题标题】:How to create dynamic plots to display on Flask?如何创建动态图以在 Flask 上显示?
【发布时间】:2017-05-18 11:57:39
【问题描述】:

我希望根据用户在烧瓶应用程序上的输入创建动态图。但是我收到以下错误: 需要字符串参数,得到“字节”

如果我使用 io.BytesIO(),我没有收到此错误,但我没有得到 test.html 上的情节

from flask import Flask
from flask import render_template
import matplotlib.pyplot as plt
import io
import base64

app = Flask(__name__)

@app.route('/plot')
def build_plot():
    img = io.StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]
    plt.plot(x,y)
    plt.savefig(img, format='png')
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())
    return render_template('test.html', plot_url=plot_url)

if __name__ == '__main__':
    app.debug = True
    app.run()

Test.html

<!DOCTYPE html>
<html>
<title> Plot</title>
<body>
<img src="data:image/png;base64, {{ plot_url }}">
</body>
</html>

【问题讨论】:

  • always in question show full error message (Traceback) 还有其他有用的信息。

标签: python flask io


【解决方案1】:

使用BytesIO 和更高版本的decode()

工作示例

from flask import Flask
#from flask import render_template
import matplotlib.pyplot as plt
import io
import base64

app = Flask(__name__)

@app.route('/plot')
def build_plot():

    img = io.BytesIO()

    y = [1,2,3,4,5]
    x = [0,2,1,3,4]
    plt.plot(x,y)
    plt.savefig(img, format='png')
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue()).decode()

    return '<img src="data:image/png;base64,{}">'.format(plot_url)

if __name__ == '__main__':
    app.debug = True
    app.run()

【讨论】:

  • 谢谢!按预期工作。
  • import matplotlib.pyplot as plt 出现错误?我该如何解决?
  • @dev 什么错误?您可能会遇到许多不同的问题。如果它无法导入matplotlib,那么可能你没有安装matplotlib - pip install matplotlibpython -m pip install matplotlib
  • @furas 谢谢。运行pip install matplotlib 已修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
相关资源
最近更新 更多