monitor_info.py 2.2 KB
# 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])

            res["data"]["memory"] = {
                'total': self.format_value(mem_total),
                'used': self.format_value(mem_used),
                'percent': "{}%".format(mem_per)
            }



            network_sent = int(psutil.net_io_counters()[0] / 8 )  # 每秒接受的kb
            network_recv = int(psutil.net_io_counters()[1] / 8 )

            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

if __name__ == '__main__':
    api = Api()
    api.process()