How to create dynamic plots to display on Flask?

烈酒焚心 提交于 2020-01-22 05:32:04

问题


I wish to create dynamic plots based on user input on a flask app. However I am getting the following error: string argument expected, got 'bytes'

If I use io.BytesIO(), I am not getting this error, but I am not getting the plot on 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>

回答1:


Use BytesIO and later decode()

Working example

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()


来源:https://stackoverflow.com/questions/41459657/how-to-create-dynamic-plots-to-display-on-flask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!