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



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

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

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

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

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

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

Flask应用程序名为";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)

名为"的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>

最新更新