为了简化操作,选用服务端框架Flask。
使用Flask完成app.py
# designed by Hilong 2022-3-3
import flask
import pymongo
from wsgiref.simple_server import make_server
app = flask.Flask(__name__)
# 连接数据库
client = pymongo.MongoClient(host='后端服务器地址')
db = client.serverinfo
@app.route('/getservername') # 可以添加, methods=['GET', 'POST'],但此处只需获取数据,默认GET即可
def getservername():
allCollections = db.list_collection_names() # 获得集合名
print("当前被监控的主机:",allCollections)
return flask.jsonify(allCollections)
@app.route('/getserverinfo/<servername>', methods=['GET', 'POST'])
def getserverinfo(servername):
collection = db[servername]
# message = list(collection.find({})) # 显示集合内所有数据
message = list(collection.find({}, {"_id": 0})) # 显示集合内所有数据并去掉_id,用于解决TypeError:ObjectId("**********") is not JSON serializable
print("获取到的服务器信息为:")
print(message)
# print(type(message))
return flask.jsonify(message)
if __name__ == "__main__":
server = make_server('0.0.0.0', 5000, app)
server.serve_forever()
app.run(host="0.0.0.0")