我有从数据库获取的数据,该数据大约超过30,000条记录,当我使用这些数据渲染模板时,模板非常慢,因此传递大量数据并在其上显示的最佳方法是什么模板。
这是我的代码。
route.py
@app.route('/index', methods=['GET', 'POST'])
def index():
asset_table = asset.query.all()
return render_template('index.html', asset_table=asset_table)
index.html
<table class="table table-hover table-sm table-striped" id="asset_table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody>
{% for asset in asset_table %}
<tr>
<td>{{ asset.asset_id }}</td>
<td>{{ asset.asset_name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function () {
$('#asset_table').DataTable({
"scrollX": true,
});
$('.dataTables_length').addClass('bs-select');
});
</script>
models.py
from application import db
class asset(db.Model):
__tablename__ = 'asset'
asset_id = db.Column(db.String(30), primary_key=True)
asset_name = db.Column(db.String(30))
答案 0 :(得分:0)
我会使用一个名为sqlalchemy-datatables的库,该库现在有点旧了,但是可以使用。
代码应如下所示:
烧瓶代码
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代码
<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>
干杯!