image.png
为了简化操作,选用服务端框架Flask。

使用Flask完成app.py

  1. # designed by Hilong 2022-3-3
  2. import flask
  3. import pymongo
  4. from wsgiref.simple_server import make_server
  5. app = flask.Flask(__name__)
  6. # 连接数据库
  7. client = pymongo.MongoClient(host='后端服务器地址')
  8. db = client.serverinfo
  9. @app.route('/getservername') # 可以添加, methods=['GET', 'POST'],但此处只需获取数据,默认GET即可
  10. def getservername():
  11. allCollections = db.list_collection_names() # 获得集合名
  12. print("当前被监控的主机:",allCollections)
  13. return flask.jsonify(allCollections)
  14. @app.route('/getserverinfo/<servername>', methods=['GET', 'POST'])
  15. def getserverinfo(servername):
  16. collection = db[servername]
  17. # message = list(collection.find({})) # 显示集合内所有数据
  18. message = list(collection.find({}, {"_id": 0})) # 显示集合内所有数据并去掉_id,用于解决TypeError:ObjectId("**********") is not JSON serializable
  19. print("获取到的服务器信息为:")
  20. print(message)
  21. # print(type(message))
  22. return flask.jsonify(message)
  23. if __name__ == "__main__":
  24. server = make_server('0.0.0.0', 5000, app)
  25. server.serve_forever()
  26. app.run(host="0.0.0.0")