monitor_info.py
2.1 KB
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
# coding=utf-8
#author: 4N
#createtime: 2021/7/9
#email: nheweijun@sina.com
from app.models import *
from app.util.component.ApiTemplate import ApiTemplate
from app.util.component.ModelVisitor import ModelVisitor
import psutil
class Api(ApiTemplate):
api_name = "监控"
def process(self):
# 返回结果
res = {}
res["data"] = {}
try:
# 业务逻辑
cpu_count = psutil.cpu_count(False)
cpu_per = int(psutil.cpu_percent())
res["data"]["cpu"] ={"count":cpu_count,"percent":"{}%".format(cpu_per)}
mem_total = int(psutil.virtual_memory()[0])
mem_used = int(psutil.virtual_memory()[3])
mem_per = int(psutil.virtual_memory()[2])
network_sent = int(psutil.net_io_counters()[0] / 8 ) # 每秒接受的kb
network_recv = int(psutil.net_io_counters()[1] / 8 )
res["data"]["memory"] = {
'total': self.format_value(mem_total),
'used': self.format_value(mem_used),
'percent': "{}%".format(mem_per)
}
res["data"]["network"] = {
'sent': self.format_value(network_sent),
'recv': self.format_value(network_recv)
}
res["result"] = True
except Exception as e:
raise e
return res
api_doc = {
"tags": ["监控接口"],
"parameters": [
],
"responses": {
200: {
"schema": {
"properties": {
}
}
}
}
}
def format_value(self,value):
if value>1024**3:
value = "{}GB".format(format(value/1024.0**3,'.1f'))
elif value>1024**2:
value = "{}MB".format(format(value / 1024.0 ** 2, '.1f'))
elif value>1024:
value = "{}KB".format(format(value / 1024.0, '.1f'))
else:
value = "{}B".format(format(value, '.1f'))
return value