在 MongoDB、Python、HTML 和 Ajax 方面需要帮助

Need assistance with MongoDB, Python, HTML, and Ajax

我很困惑,我已经搜索过了,但似乎找不到我要找的东西。我的客户希望在 HTML table 中查看 MongoDB 数据,最好使用 DataTables 和 Ajax.

问题是我发现的方法将所有数据保存到 HTML 导致它需要很长时间才能加载。

另一种方法是将数据作为 .json 存储在他们的数字服务器上,但是一旦 .json 超过 1,000 kb,他们的服务器就会开始滞后。

所以我的问题是,是否有另一种方法可以查看 HTML 中的数据,而无需将其直接附加到 HTML 中或将其作为 .json 导出到他们的服务器?

他们的数字服务器使用 Python 2.7 和 Ubuntu 20.04.2。

我想到了这个。我将不胜感激任何修改以使其更好。我仍然是编码的初学者,这是我通过研究学到的,所以如果它缺少任何关键组件,我提前道歉。

名为“record.py”的 Flask 应用程序

#!/usr/bin/env python
# coding: utf-8
from flask import Flask, request, render_template, abort, jsonify, Response
import pymongo
import logging
import json
from bson.objectid import ObjectId
from bson import json_util
from pymongo import MongoClient
from flask_pymongo import PyMongo

class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)
        return super(MyEncoder, self).default(obj)

# client = pymongo.MongoClient("mongodb+srv://<Username>:<password>@<cluster_name_all_lowercase>.wncwk.mongodb.net/<Cluster_Name>?retryWrites=true&w=majority")

client = pymongo.MongoClient("mongodb+srv://<Username>:<password>@<cluster_name_all_lowercase>.wncwk.mongodb.net/<Cluster_Name>?retryWrites=true&w=majority")
mydb = client["bs"] # Database name
msgs = mydb["ChatEST"] # Collection name

app = Flask(__name__)
app.json_encoder = MyEncoder

@app.route('/')
def index():
  return render_template('chatmsg.html')

@app.route('/ChatEST')
def Msgs():
    ChatEST = list(msgs.find({}))
    from bson.objectid import ObjectId
    return json.dumps(ChatEST, default = json_util.default)
     
if __name__ == '__main__':
    app.run("0.0.0.0", 4884, debug = True)

HTML 模板名为“chatmsg.html”

<!DOCTYPE html>
 <html lang="en">
 <script src="{{ url_for('static', filename='jquery-3.5.1.min.js') }}"></script>
 <script type="text/javascript" src="{{ url_for('static', filename='jquery.dataTables.min.js') }}"></script>
 <script type="text/javascript" src="{{ url_for('static', filename='bootstrap.min.js') }}"></script>
 <head lang="en">
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
     <link rel="stylesheet" href="{{ url_for('static', filename='thegr8.css') }}"/> /* Custome CSS file */
     <link rel="stylesheet" href="{{ url_for('static', filename='bootstrap.min.css') }}"/>
     <link rel="stylesheet" href="{{ url_for('static', filename='jquery.dataTables.min.css') }}"/>
     <title>Title</title>
     <style>
     {padding-top: 1.25%; padding-right: 0.25%; padding-bottom: 1.25%; padding-left: 0.25%;}
     </style>
 </head>
 <center></span><div class="table-responsive"></div></span></center>
     <table id="chatTable" class="display" width="100%" style="height:auto;width:100%;min-width:1%;font-size:2vw;background-color:rgba(0,0,0,0.25)">
         <thead>
             <tr>
                 <th class="sorttable_alpha" width=auto>Name</th>
                 <th class="sorttable_alpha" width=auto>Message</th>
                 <th class="sorttable_alpha" width=auto>Date</th>
                 <th class="sorttable_alpha" width=auto>Account ID</th>
                 <th class="sorttable_alpha" width=auto>Global ID</th>
             </tr>
         </thead>
         <tfoot>
             <tr>
                 <th class="sorttable_alpha" width=auto>Name</th>
                 <th class="sorttable_alpha" width=auto>Message</th>
                 <th class="sorttable_alpha" width=auto>Date</th>
                 <th class="sorttable_alpha" width=auto>Account ID</th>
                 <th class="sorttable_alpha" width=auto>Global ID</th>
             </tr>
         </tfoot>
     </table>
 <script>
 function setupData() {
     $(document).ready(function () {
         var table = $('#chatTable').DataTable({
             initComplete: function () {
                 api = this.api();
                 this.api().columns().every( function () {
                     api.order.listener($(this.footer()), this.index(), null);
                    });
                },
             "ajax": {
                 // "url": "static/objects2.txt", // This works for the static file.
                 "url": "/ChatEST", // This now works too thanks to @kthorngren
                 "dataType": "json",
                 "dataSrc": ""},
                 "columns": [
                     { "data": "name", "name": "name"},
                     { "data": "msg", "name": "msg" },
                     { "data": "msgTime", "name": "msgTime", "defaultContent": "" },
                     { "data": "player", "name": "player" },
                     { "data": "accountID", "name": "accountID",
                        fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                            if(oData.player) {
                                $(nTd).html("<a href=http://Creating_a_link_with_a_piece_of_the_data.com"+oData.accountID+" target='_blank' rel='noopener noreferrer'>"+ "GID" +"</a>");
                            }
                        }
                    },
                ],
                lengthMenu: [ [3, 5, 8, 33, 55, 88, 1000], [3, 5, 8, 33, 55, 88, 1000] ], // Need help making this dynamic so as the .json data increases the Length Menu number also increases.
                pageLength: 3,
                paging: true,
                deferRender: true,
                responsive: true,
                scrollY: 300,
                scrollCollapse: true,
                scroller: {rowHeight: 10}
            });
        });
    }
 $( window ).on( "load", setupData );
 </script>
 </body>
</html>