Created
September 4, 2018 22:46
-
-
Save pmav99/749ebd630bbe2b69e937ee87a26124a5 to your computer and use it in GitHub Desktop.
Flask + datatables + ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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