7

I was wondering if there might be a way to return my Flask app's response as an HTML table populated by the JSON response key value pairs instead of merely having the entire JSON string on the HTML page?

Below is the code that i have:

from flask import Flask
import json, pandas as pd

app = Flask(__name__)

@app.route("/GetData")
def GetData():
    df = pd.read_csv("DemoData.csv")
    temp = df.to_dict('records')
    data = [dict(i) for i in temp]
    return json.dumps(data, indent=4)


if __name__ == "__main__":
    app.run(host='127.0.0.1', port=8000)

The code above gives the following response: (URL: "http://127.0.0.1:8000/GetData")

current output

Now what i want is to get the response converted into a table upon entering the aforementioned URL kinda like the CSV file.

Here is a sample of my CSV file:

Employee Name,City,Country,Project Assigned
Carl Elias,Passadena,USA,Optical Character Recognition
Amanda Jean Spears,Denver,USA,Linux Kali Security Mods
John Reese,Athens,Greece,Inertial Navigation System
Leslie James,Heartfordshire,United Kingdom,Relay Transmission Optimisation Mods
Patrick Sullivan,London,United Kingdom,Fraud Checking System
Julia Reginald Roberts,Sao Paolo,Brazil,User Authentication System
Michael Bucannan,San Franscisco,USA,Analytics Automation Tool
Jeanine Fitzgerald,Ontario,Canada,CopyChecker
Patricia Sullly,Shanghai,China,Automated Milling Tool
5
  • 1
    Write a template. flask.pocoo.org/docs/0.12/tutorial/templates Commented Apr 22, 2018 at 9:16
  • @AlexHall but wouldn't that restrict me to hardcode html according to the current csv file like wouldn't that require to have an advance knowledge of what are the coloumn names in the csv, isn't there a dynamic way .. Commented Apr 22, 2018 at 9:20
  • @AlexHall suppose i change my csv file then wouldn't that create problems while displaying the table because the table would be hard coded to display the previous csv coloumns Commented Apr 22, 2018 at 9:21
  • 1
    No, df.columns has the CSV columns in order, you can use them in your template. Commented Apr 22, 2018 at 9:27
  • You can loop over the columns in your CSV (a dict isn't ordered, don't use one for this task) and simply create the HTML for a table, that wouldn't be hard. Commented Apr 22, 2018 at 9:27

3 Answers 3

10

You should write a template for it like Alex Hall said. It won't be hardcoded if you loop through column names. Firstly, you should import render_template.

from flask import Flask, render_template

Then, you need to change your request handler. This allows to render a template 'record.html' with injecting two variables, records and colnames.

@app.route("/GetData")
def GetData():
    df = pd.read_csv("DemoData.csv")
    temp = df.to_dict('records')
    columnNames = df.columns.values
    return render_template('record.html', records=temp, colnames=columnNames)

Check this rendering template guide. You need to create a new folder 'templates/', and you can find 'templates/record.html' below:

<table border="1">
    <thead>
        <tr>
            {% for col in colnames %}
            <th>{{ col }}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        {% for record in records %}
        <tr>
            {% for col in colnames %}
            <td>{{ record[col] }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

To do this dynamically, firstly you should iterate through column names. As Alex Hall said, dict is not ordered so when iterating records, you should also iterate column names, so you can write them in right order.

Sign up to request clarification or add additional context in comments.

Comments

4

A really simple hack is read data into a pandas dataframe first, then call .to_html:

import pandas as pd
from flask import Flask, render_template

@app.route("/table-page", methods=['GET'])
def table():

    data_dic = {
        'id': [100, 101, 102],
        'color': ['red', 'blue', 'red']}
    columns = ['id', 'color']
    index = ['a', 'b', 'c']

    df = pd.DataFrame(data_dic, columns=columns, index=index)
    table = df.to_html(index=False)
    
    return render_template(
        "at-leaderboard.html",
        table=table)

Then simply pop the HTML into your template:

<html>
  <body>
    <div>
      {{ table | safe }}
    </div>
  </body>
</html>

Comments

1

To convert JSON data into HTML table that can be displayed on a web page I followed these steps:

  1. Load .json file into a python object using json.load
  2. Convert python object to HTML table using json2html.convert
  3. Render data_table in index.html as
 <div id="content-database">
        {{ data_table | safe }}
 </div>

This avoids writing any for-loops in HTML code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.