How to pass massive data from flask to template?
I would use a library called sqlalchemy-datatables which is a bit old now but does it work.
The code should look like this:
Flask Code
from datatables import ColumnDT, DataTables@app.route('/index', methods=['GET'])def index(): """ Code which renders the index page """ return render_template('index.html')@app.route('/data', methods=['GET'])def data(): """ Returns data for the index page. GET: params: Please learn about the other parameters here: https://datatables.net/manual/server-side#Sent-parameters responses: Please learn about the response parameters here: https://datatables.net/manual/server-side#Returned-data """ columns = [ ColumnDT( asset.asset_id, mData="ID" ), ColumnDT( asset.asset_name, mData="Name" ) ] query = db.session.query().select_from(asset) params = request.args.to_dict() rowTable = DataTables(params, query, columns) return jsonify(rowTable.output_result())
HTML/Jquery Code
<table class="table table-hover table-sm table-striped" id="asset_table"> <thead class="thead-dark"> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody></tbody> </table><script>$(document).ready(function () { $('#asset_table').DataTable({ processing: true, serverSide: true, ajax: "{{ url_for('data')}}", dom: 'Bflrtip', columns: [ { "data": "ID" }, { "data": "Name" },] }); });</script>
Cheers!