This article mainly introduces some examples of a memory monitoring program using the Flask framework of Python combined with MySQL, and can display the results in a simple graphical way, for more information about how to monitor memory usage, see the following demo program.
I. create databases and tables
Create a falcon database:
mysql> create database falcon character set utf8;Query OK, 1 row affected (0.00 sec)
Create a table stat for memory monitoring. The table structure is as follows:
CREATE TABLE `stat` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `host` varchar(256) DEFAULT NULL, `mem_free` int(11) DEFAULT NULL, `mem_usage` int(11) DEFAULT NULL, `mem_total` int(11) DEFAULT NULL, `load_avg` varchar(128) DEFAULT NULL, `time` bigint(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `host` (`host`(255))) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
Ii. flask web terminal settings
First, we design a web service to implement the following functions:
Complete monitoring page display
Accept data submitted by POST
Json data GET Interface
The framework structure is as follows:
The directory structure is as follows:
web├── flask_web.py└── templates └── mon.html
The flask_web code is as follows:
import MySQLdb as mysqlimport jsonfrom flask import Flask, request, render_templateapp = Flask(__name__)db = mysql.connect(user="361way", passwd="123456", \ db="falcon", charset="utf8")db.autocommit(True)c = db.cursor()@app.route("/", methods=["GET", "POST"])def hello(): sql = "" if request.method == "POST": data = request.json try: sql = "INSERT INTO `stat` (`host`,`mem_free`,`mem_usage`,`mem_total`,`load_avg`,`time`) VALUES('%s', '%d', '%d', '%d', '%s', '%d')" % (data['Host'], data['MemFree'], data['MemUsage'], data['MemTotal'], data['LoadAvg'], int(data['Time'])) ret = c.execute(sql) except mysql.IntegrityError: pass return "OK" else: return render_template("mon.html")@app.route("/data", methods=["GET"])def getdata(): c.execute("SELECT `time`,`mem_usage` FROM `stat`") ones = [[i[0]*1000, i[1]] for i in c.fetchall()] return "%s(%s);" % (request.args.get('callback'), json.dumps(ones))if __name__ == "__main__": app.run(host="0.0.0.0", port=8888, debug=True)
The graph JS used here is highcharts and highstock. The specific template content is as follows:
[root@91it templates]# cat mon.html
Memory monitor
Highstock Example