如何渲染并返回绘图以在烧瓶中查看?

5 python flask seaborn

如何在视图中渲染绘图flask

devices.py:

@devices_blueprint.route('/devices/test/')

def test():
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]
    plot_url = plt.plot(x,y)
    return render_template('devices/test.html', plot_url=plot_url)
Run Code Online (Sandbox Code Playgroud)

的test.html

<div class="container">
      <h2>Image</h2>    
      <img src= {{ resized_img_src('plot_url') }} class="img-rounded" alt="aqui" width="304" height="236"> 
    </div>
Run Code Online (Sandbox Code Playgroud)

我试图seaborn用这个,但即使matplolib我无法得到任何结果.

注意:我不想保存图像并在之后加载它.

And*_*reL 8

有了matplotlib你可以这样做:

#Add this imports
import StringIO
import base64

@devices_blueprint.route('/devices/test/')
def test():

    img = StringIO.StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)

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

    return render_template('test.html', plot_url=plot_url)
Run Code Online (Sandbox Code Playgroud)

在你的 HTML 中输入:

<img src="data:image/png;base64, {{ plot_url }}">
Run Code Online (Sandbox Code Playgroud)

如果你想使用seaborn,你只需要import seaborn设置你想要的样式,例如

...
import seaborn as sns
...

@devices_blueprint.route('/devices/test/')
def test():

    img = StringIO.StringIO()
    sns.set_style("dark") #E.G.

    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)

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

    return render_template('test.html', plot_url=plot_url)
Run Code Online (Sandbox Code Playgroud)