python学习-Flask使用SocketIO结合Echarts实现一个简单的实时监控图

2019 Java 开发者跳槽指南.pdf (吐血整理)….>>>
后台实现代码runserver.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#encoding:utf-8
#!/usr/bin/env python
import psutil
import time
from threading import Lock
from flask import Flask, render_template
from flask_socketio import SocketIO
 
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
 
# 后台线程 产生数据,即刻推送至前端
def background_thread():
    count = 0
    while True:
        socketio.sleep(5)
        count += 1
        t = time.strftime('%M:%S', time.localtime())
        # 获取系统时间(只取分:秒)
        cpus = psutil.cpu_percent(interval=None, percpu=True)
        # 获取系统cpu使用率 non-blocking
        socketio.emit('server_response',
                      {'data': [t, cpus], 'count': count},
                      namespace='/test')
        # 注意:这里不需要客户端连接的上下文,默认 broadcast = True
 
 
@app.route('/')
def index():
    return render_template('index.html', async_mode=socketio.async_mode)
 
@socketio.on('connect', namespace='/test')
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)
 
if __name__ == '__main__':
    socketio.run(app, debug=True)
前台页面模版:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>系统监控走势图</title>
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="//cdn.bootcss.com/socket.io/1.5.1/socket.io.min.js"></script>
    <!-- ECharts 3 引入 -->
    <script src="http://echarts.baidu.com/dist/echarts.min.js"></script>
</head>
 
<body>
    <div id="main" style="height:500px;border:1px solid #ccc;padding:10px;"></div>
 
    <script type="text/javascript">
 
    var myChart = echarts.init(document.getElementById('main'));
 
    myChart.setOption({
        title: {
            text: '系统监控走势图'
        },
        tooltip: {},
        legend: {
            data:['cpu']
        },
        xAxis: {
            data: []
        },
        yAxis: {},
        series: [{
            name: 'cpu',
            type: 'line',
            data: []
        }]
    });
 
 
    var time = ["","","","","","","","","",""],
        cpu = [0,0,0,0,0,0,0,0,0,0]
 
 
    //准备好统一的 callback 函数
    var update_mychart = function (res) {
    //res是json格式的response对象
 
        // 隐藏加载动画
        myChart.hideLoading();
 
        // 准备数据
        time.push(res.data[0]);
        cpu.push(parseFloat(res.data[1]));
        if (time.length >= 10){
            time.shift();
            cpu.shift();
        }
 
        // 填入数据
        myChart.setOption({
            xAxis: {
                data: time
            },
            series: [{
                name: 'cpu', // 根据名字对应到相应的系列
                data: cpu
            }]
        });
 
    };
 
    // 首次显示加载动画
    myChart.showLoading();
 
 
    // 建立socket连接,等待服务器“推送”数据,用回调函数更新图表
    $(document).ready(function() {
        namespace = '/test';
        var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
 
        socket.on('server_response', function(res) {
            update_mychart(res);
        });
 
    });
 
    </script>
</body>
</html>
实现的效果: