Matt_Haythornthwaite
Matt_Haythornthwaite

Reputation: 753

Passing variables from python server to HTML using Flask

I'm looking to build a basic website using Flask to display predictions from a python machine learning project. I have the following file structure:

project/
    static/
        style.css
        script.js
    templates/
        index.html
    server.py

And I'm looking to pass the predictions from my server.py into my index.html

The predictions are stored in a Pandas DataFrame in the following format:

      P1     P2
0     60     40
1     26     74

I've managed to pass this data into my index.html with the following code in my server.py file:

a = df['P1'][0]
b = df['P2'[0]
c = df['P1'][1]
d = df['P2'[1]

@app.route('/')
def pass_data():
    return render_template('index.html', a=a, b=b, c=c, d=d)

In reality I have far more predictions I wish to display in my index.html. So my question is, is there a better, more efficient way to pass data from my DataFrame into my index.html, as opposed to defining each one individually and passing them in the return command of the pass_data() function.

Appreciate any recommendations, cheers!

Upvotes: 0

Views: 41

Answers (1)

Balaji Ambresh
Balaji Ambresh

Reputation: 5012

How about passing the entire dataframe?

In the python file

return render_template('index.html', df=df)

Inside body tag inside index.html

{{ df.to_html() | safe }}

Upvotes: 2

Related Questions