Skip to content

Instantly share code, notes, and snippets.

@pmav99
Created September 4, 2018 22:46
Show Gist options
  • Select an option

  • Save pmav99/749ebd630bbe2b69e937ee87a26124a5 to your computer and use it in GitHub Desktop.

Select an option

Save pmav99/749ebd630bbe2b69e937ee87a26124a5 to your computer and use it in GitHub Desktop.
Flask + datatables + ajax
import numpy as np
import pandas as pd
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
MY_DATA = pd.DataFrame(np.random.random((10000, 3)), columns=["a", "b", "c"])
@app.route('/index')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/index_get_data')
def stuff():
data = {"data": MY_DATA.to_dict("records")}
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Datatables Example</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h1>My Heading</h1>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tfoot>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</tfoot>
</table>
<script>
function setupData() {
$(document).ready(function () {
$('#example').DataTable({
"ajax": {
// "url": "static/objects2.txt", // This works for a static file
"url": "/index_get_data", // This now also works
"dataType": "json",
"dataSrc": "data",
"contentType":"application/json"
},
"columns": [
{"data": "a"},
{"data": "b"},
{"data": "c"},
]
});
});
}
$( window ).on( "load", setupData );
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment