简体   繁体   中英

Render graph from Python / Flask to HTML using Jinja2

I have written bunch of code but it is not rendering the chart inside HTML for some reason. Program however runs and creates an image in Static folder. Can someone tell me how I can pass this "image" in Jinja2 in in HTML in order to view it in HTML? Flask code:

@app.route('/', methods=['GET', 'POST'])
def index():
image = False
from flask import Flask, render_template, request
if request.method == 'POST':
    a = int(request.form['a'])
    x = np.linspace(-20, 20, 20)
    y = a * x 
    plt.plot(x,y)
    plt.savefig('C:/Users/name/PycharmProjects/qtcalc1/static/image.png')
    image = url_for('static', filename = image)
    print(image)
    plt.show()

return render_template('graphtry.html', image = image)

Note view function code is indented well on my end. I need solution for how to render this image in my HTML file graphtry.html using Jinja2. My current HTML code is as follows:

<img src ="{{image}}" >

When you write

image = url_for('static', filename = image)

the value of image variable in the argument is False (from line 3). You have to pass the actual filename, that is in this example: image.png .

image = url_for('static', filename='image.png')

And also, remove the extra space after src attribute:

<img src="{{image}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM