簡體   English   中英

如何將flask中的海量數據傳遞給模板?

[英]How to pass massive data from flask to template?

我有從數據庫中獲取的數據,數據大約有 30,000 多條記錄,當我用這些數據渲染模板時,模板非常慢,那么傳遞大量數據並在模板上顯示的最佳方法是什么。

這是我的代碼。

路線.py

@app.route('/index', methods=['GET', 'POST'])
def index():
  asset_table = asset.query.all()
  return render_template('index.html', asset_table=asset_table)

索引.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>

模型.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))


我會使用一個名為sqlalchemy-datatables的庫,它現在有點舊,但它可以工作。

代碼應如下所示:

Flask 代碼

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>

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM