Use Python's flask framework to combine MySQL with some memory monitor program

Source: Internet
Author: User
Here to monitor memory usage as an example, write a simple demo program, the specific operation according to the 51reboot provided by the tutorial written as follows.

First, build a database to build a table

To create a Falcon database:

Mysql> CREATE DATABASE Falcon character set UTF8; Query OK, 1 row Affected (0.00 sec)

To create a memory monitor using the table stat, the table structure is as follows:

CREATE TABLE ' stat ' (' id ' int (one) unsigned not NULL auto_increment, ' host ' varchar () DEFAULT NULL, ' mem_free ' int (11) Default NULL, ' Mem_usage ' int (one) default null, ' Mem_total ' int (one) default null, ' LOAD_AVG ' varchar (+) default NULL, ' t IME ' bigint (one) default NULL, PRIMARY key (' ID '), key ' host ' (' Host ' (255))) Engine=innodb auto_increment=0 default CHARSET =utf8;

Second, flask web-side settings

First we design a Web service that implements the following functions:

Complete the Monitoring page display
Accept post-submitted data
Provides a JSON data get interface
The specific 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 = "in SERT 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"]) d EF GetData (): C.execute ("Select ' Time ', ' mem_usage ' from ' stat '") ones = [[i[0]*1000, i[1]] for i in C.fetchall ()] Retur N "%s" (%s); "% (Request.args.get (' callback '), json.dumps (ones)) if __name__ = =" __main__ ": App.run (host=" 0.0.0.0 ", port= 8888,Debug=true) 

Here the use of the map JS for Highcharts, Highstock, the specific template page content is as follows:

[Root@91it templates]# Cat mon.html

Memory Monitor      
 
      Highstock Example    
 
                  
 
  
 
    

Note: The JS code here is directly using the code on the Internet, if the host can not connect to the Internet, the above three segments will be taken down, in the templates's sibling directory to create a static directory, the downloaded three files into the directory, Delete the code from three references in the template, using the three segment of the current comment.

Third, agent is monitored by the terminal settings

The Web presentation page is complete and running: Python flask_web.py is listening on port 8888. We need to do an agent to collect data, and through the Post method request Flask_web page, upload data to the database. Here, for example, monitoring memory, the specific monitoring code is as follows:

#!/usr/bin/env python#coding=utf-8import inspectimport timeimport urllib, urllib2import jsonimport socketclass mon:def __init__ (self): Self.data = {} def getTime (self): return str (int. (Time.time ()) + 8 * 3600) def gethost (self): RE Turn socket.gethostname () def getloadavg (self): with open ('/proc/loadavg ') as Load_open:a = Load_open.read (). SPL It () [: 3] return ', '. Join (a) def getmemtotal (self): with open ('/proc/meminfo ') as mem_open:a = Int (mem_open. ReadLine (). Split () [1]) return a/1024 def getmemusage (self, nobuffercache=true): if Nobuffercache:with ope N ('/proc/meminfo ') as Mem_open:t = Int (Mem_open.readline (). Split () [1]) F = Int (Mem_open.readline (). Split () [ 1]) B = Int (Mem_open.readline (). Split () [1]) C = Int (Mem_open.readline (). Split () [1]) return (T-F-B-C)/ 1024x768 Else:with open ('/proc/meminfo ') as mem_open:a = Int (Mem_open.readline (). Split () [1])-INT (MEM_OPEN.R    Eadline (). Split () [1])    Return a/1024 def getmemfree (self, nobuffercache=true): If Nobuffercache:with open ('/proc/meminfo ') as Mem _open:t = Int (Mem_open.readline (). Split () [1]) F = Int (Mem_open.readline (). Split () [1]) B = Int (mem_op En.readline (). Split () [1]) C = Int (Mem_open.readline (). Split () [1]) return (f+b+c)/1024 Else:with ope N ('/proc/meminfo ') as Mem_open:mem_open.readline () a = Int (Mem_open.readline (). Split () [1]) return a /1024x768 def runallget (self): #自动获取mon类里的所有getXXX方法, use XXX as the return value of key,getxxx () as value, to construct the dictionary for fun in Inspect.getmembers ( Self, Predicate=inspect.ismethod): if fun[0][:3] = = ' Get ': self.data[fun[0][3:]] = fun[1] () return Self.dat AIF __name__ = = "__main__": While true:m = Mon () data = M.runallget () print data req = Urllib2. Request ("http://test.361way.com:8888", Json.dumps (data), {' Content-type ': ' Application/json '}) F = Urllib2.urlopen ( Req) response = F.read () Print RESPOnse f.close () time.sleep (60) 

Nohup python moniitems.py >/dev/null 2>&1 & run on the monitored host, if for experimental purposes, want to see the display effect as soon as possible, you can time.sleep (60) Change to Time.sleep (2) so that data is written to the database every 2 seconds.

Visit http://test.361way.com:8888 to see our monitoring data: the following

Highcharts support will be dragged by time and also supported by a specified time period. And the images you see can be saved directly to PNG, JPG or PDF, CSV and other formats to view.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.