Getting Flask JSON response as an HTML Table? Getting Flask JSON response as an HTML Table? flask flask

Getting Flask JSON response as an HTML Table?


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.


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

import pandas as pdfrom 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>