Kiwi
Kiwi

Reputation: 81

Data created with class failes to be displayed with flask app into html

I'm tring to make a flask application for a tool that I've created in my internship. I have a class Activities that can generate a pandas dataframe, and I wish to display it into a table in an HTML using flask. I tested a simple example that works just fine and displays the given dataframe, but as soon as I try doing the same thing with Activites class, it doesn't work. The code in itself doesn't result in any errors in the kernel but when I go to http://localhost:5000/, my web browser(Chrome) says localhost does not allow the connection : ERR_CONNECTION_REFUSED. The class takes up to 15 minutes just to create the data, I was thinking that maybe the Chrome does not like to wait such a long time and just refuses the connection ? I am new with Flask so I am very confused. Thank you for your help :)

This is the simple working code :

import pandas as pd
from flask import Flask, redirect, url_for, request, render_template

app = Flask(__name__) 

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c', 'd', 'e']})

@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html')

@app.route('/task1')
def task1():
    return render_template('task1.html')

@app.route('/handle_data', methods=['POST'])
def handle_data():
    return render_template('simple.html', tables=[df.to_html(classes='data')], titles=df.columns.values)

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

This is what I'm trying to do that doesn't work :

import pandas as pd
from flask import Flask, redirect, url_for, request, render_template
from activities import Activities

app = Flask(__name__) 

activities = Activities()

activities.load_data()

df = activities.raw_data.head()

@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html')

@app.route('/task1')
def search_for_sailors():
    return render_template('task1.html')

@app.route('/handle_data', methods=['POST'])
def handle_data():
    return render_template('simple.html', tables=[df.to_html(classes='data')], titles=df.columns.values)

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

Upvotes: 1

Views: 82

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31226

Approach that I use for data that takes time to get back to client is AJAX to get data post page load.

  1. changed /handle_data route to respond to GET plus move heavy lifting build of data frame into it (logically)
  2. use Response() flask object to return html of data frame
  3. use JQuery to do AJAX call to this /handle_data route to get HTML of table

app.py

import pandas as pd
from flask import Flask, redirect, url_for, request, render_template, Response

app = Flask(__name__)

@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html')

@app.route('/task1')
def task1():
    return render_template('task1.html')

@app.route('/handle_data')
def handle_data():
    df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                       'B': [5, 6, 7, 8, 9],
                       'C': ['a', 'b', 'c', 'd', 'e']})
    return Response(df.to_html())

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

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Example</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
            integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
            crossorigin="anonymous"></script>
</head>
<body>
    <header>
        <h1>Header 1</h1>
    </header>
    <main id="main">
        <section id="data-section">
            <h2>Data</h2>
            <div id="data"/>
        </section>
    </main>
</body>
<script>
    function apicall(url) {
        $.ajax({
            type:"GET",
            url:url,
            success: (data) => {
                $("#data").html(data);
            }
        });
    }

  window.onload = function () {
    apicall("/handle_data");
  }
</script>
</html>

Upvotes: 1

Related Questions