【问题标题】:Need assistance with MongoDB, Python, HTML, and Ajax在 MongoDB、Python、HTML 和 Ajax 方面需要帮助
【发布时间】:2021-05-27 23:13:09
【问题描述】:

我很难过我已经搜索过,但我似乎找不到我要找的东西。我的客户想要在 HTML 表中查看 MongoDB 数据,最好使用 DataTables 和 Ajax。

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

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

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

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

【问题讨论】:

  • 假设您对数据表使用分页,您可能需要考虑延迟加载,并使用数据库游标。仅获取初始页面所需的记录,但保持光标打开。当用户导航到下一页时,他们从数据库中获取下一组,因此加载延迟分布在每个页面请求中。
  • 跟进延迟加载方法:如果您尝试将所有数据预先发送到 DataTables(假设数千/百万条记录)。最典型的解决方案(如果您坚持使用 DataTables)是使用server-side processing。好处是:这应该表现良好,因为您一次只向浏览器发送一页结果。缺点是:服务器需要实现所有的分页、排序和过滤逻辑。
  • 当 HTML 使用 .json 文件时,DataTables 可以正常工作。但是当表格的每一行都保存在 HTML 中时,加载需要很长时间。所以我想使用 .json 但它不能存储在服务器上,因为这会导致服务器滞后。我认为 MongoDB 可能是解决方案,但我似乎无法弄清楚如何在不将数据作为 .json 保存到服务器或将其附加到 HTML 的情况下显示来自 MongoDB 的数据。
  • 加载时间很长” - 同意 - 这听起来像是支持服务器端处理的论据。 “它(json)不能存储在服务器上”——JSON 不需要存储在服务器上——也许你可以澄清一下你的意思?
  • 当 JSON 保存在服务器上时,服务器遇到了延迟,这意味着服务器正在运行的程序存在延迟,因为 JSON 的文件大小很大。我做了一些测试,发现一旦 JSON 达到超过 1,000 KB 的量,就会开始延迟。

标签: python html mongodb flask datatables


【解决方案1】:

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

名为“record.py”的烧瓶应用

#!/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)

名为“chatmsg.html”的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多