I want to display a table - which is a pandas dataframe - as a DataTable. In the simplified example below, I read two numbers provided by a user, that determine the row and column number of the table. The number of elements of this table is then displayed correctly, however, the table does not appear.
The problem is, I think, that I pass the table in the wrong way. When I try
return jsonify(number_elements=a * b,
my_table=df)
I get the error
anaconda2/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 0 1 2 3 0 51 35 10 84 1 30 60 79 24 is not JSON serializable
if I use
return jsonify(number_elements=a * b,
my_table=df.to_json())
then there is no error but the table is still not displayed.
How would I do this correctly?
My index.html
file looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"
rel="stylesheet">
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON('/_get_table', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#elements").text(data.number_elements);
$("#a_nice_table").DataTable(data.my_table);
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Create a pretty table</h3>
</div>
<div>
<p>Number of rows</p>
<input type="text" size="5" name="a" value="2">
<p>Number of columns</p>
<input type="text" size="5" name="b" value="4">
<p><a href="javascript:void();" id="calculate">get a pretty table</a></p>
<p>Result</p>
<p>Number of elements:</p>
<span id="elements">Hallo</span><br>
<span id="a_nice_table">Here should be a table</span>
</div>
</div>
</body>
</html>
And my file app.py
looks like this:
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
# Initialize the Flask application
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_get_table')
def get_table():
a = request.args.get('a', type=int)
b = request.args.get('b', type=int)
df = pd.DataFrame(np.random.randint(0, 100, size=(a, b)))
return jsonify(number_elements=a * b,
my_table=df)
if __name__ == '__main__':
app.run(debug=True)