Python + Flask 实现接口接收 Disk 信息

今天分享的内容是基于:Python + Flask 实现接口接收内存信息 来进一步分享如何使用 Python + Flask 实现接收 Disk 的信息。

 

原理:

通过 Python 调用 Shell 脚本去执行 Disk 的相关命令,然后进行处理再请求 Requests 库来向后端定义好的接口推送数据。

 

Part1:收集端

 1 import os
 2 import requests
 3 import json
 4 import time
 5  
 6 url="http://10.8.31.61:5555/GetDiskResource"
 7 mem_data={}
 8 mem_cmd = [
 9 "df -h |grep home |awk -F' ' '{print $2}'",
10 "df -h |grep home |awk -F' ' '{print $3}'",
11 "df -h |grep home |awk -F' ' '{print $4}'"
12 ]
13 def exec_cmd():
14     for cmd in mem_cmd:
15         print(cmd)
16         response = os.popen(cmd)
17         if("$2" in cmd):
18             mem_data['total']=str(response.read()).replace("\n","")
19         elif("$3" in cmd):
20             mem_data['used']=str(response.read()).replace("\n","")
21         elif("$4" in cmd):
22             mem_data['available']=str(response.read()).replace("\n","")
23     else:
24         mem_data['hostname']=str(os.popen("hostname |awk -F'.' '{print $1}' |awk -F'-' '{print $2}'").read()).replace("\n","")
25     response.close()
26  
27 def httpPost(datas):
28     header = {"Content-Type":"application/json"}
29     resp_content = requests.post(url=url,data=json.dumps(datas),headers=header)
30     print(resp_content.text)
31  
32 if __name__ == '__main__':
33     while True:
34         exec_cmd()
35         httpPost(mem_data)
36         time.sleep(3600)

 

Part2:接收端

 1 #磁盘路由处理-------------------------------------------------------
 2 @resource.route('/GetDiskResource',methods=['POST'])
 3 def GetDiskResource():
 4     '''接收来自linux上传的数据'''
 5     query = request.get_json()
 6     hostname = query["hostname"]
 7     total = query["total"]
 8     used = query["used"]
 9     available = query["available"]
10     createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
11     sql = "insert into disk_info (hostname,total,used,available,create_time) VALUES "
12     data = "('" + hostname + "','" + total + "','" + used + "','" + available +  "','" + str(createtime) + "'"
13     end = data + ")"
14     sql = sql + end
15     print(sql)
16     db = conndb()
17     db.execute_sql(sql)
18     data = {'code': 200, 'message': 'success', 'status': '10000'}
19     return json.dumps(data)

 

Part3:展示端

这部分主要分为以下两块内容:

第一块是页面请求

<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 磁盘信息
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.hostname" placeholder="环境" class="handle-input mr10" clearable @clear="clear_name"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header">
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="hostname" label="环境"></el-table-column>
                <el-table-column prop="total" label="总共"></el-table-column>
                <el-table-column prop="used" label="使用掉"></el-table-column>
                <el-table-column prop="available" label="可用">
                  <template #default="scope">
                        <el-tag :type="availableplus(scope.row.available) === 'success' ? 'success': 'danger'">{{ scope.row.available }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="create_time" width="160" label="创建时间"></el-table-column>
            </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="query.pageIndex"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="query.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="parseInt(pageTotal)">
          </el-pagination>
        </div>
    </div>
</template>
 
<script>
import server from '../api/request.js'
export default {
  name: 'InterfaceMem',
  data () {
    return {
      query: {
        hostname: '',
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      pageTotal: 0
    }
  },
  created () {
    this.getDiskData()
  },
  methods: {
    // 获取后端返回的真实数据
    getDiskData () {
      server({url: '/getDiskList', data: this.query, method: 'post'})
        .then(response => {
          console.log('**********')
          console.log(response)
          this.tableData = response.listdata
          console.log(this.tableData)
          this.pageTotal = response.pageTotal || 10
        })
    },
    // 触发搜索按钮
    handleSearch () {
      server({url: '/getDiskList', data: this.query, method: 'post'})
        .then(response => {
          console.log(response)
          this.tableData = response.listdata
          console.log(this.tableData)
          this.pageTotal = response.pageTotal || 10
        })
    },
    // 分页导航
    handleSizeChange (val) {
      // console.log(val)
      this.$set(this.query, 'pageSize', val)
      // console.log(this.query)
      this.getDiskData()
    },
    // 翻页改变页码触发
    handleCurrentChange (val) {
      this.$set(this.query, 'pageIndex', val)
      this.getDiskData()
    },
    clear_name () {
      this.query.hostname = ''
      this.getDiskData()
    },
    availableplus(rows){
      const availabl =rows.replace("G","")
      return Number(availabl) <15 ? 'danger' : 'success'
    }
  }
}
</script>
 
<style scoped>
.handle-box {
    margin-bottom: 20px;
}
 
.handle-select {
    width: 120px;
}
 
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>

 

第二块是后端请求处理

 1 @resource.route('/getDiskList',methods=['POST'])
 2 def getDiskList():
 3     '''fe的页面列表数据获取'''
 4     query = request.get_json()
 5     print(query)
 6     if (query["hostname"] == ""):
 7         sql1 = "select id,hostname,total,used,available,create_time from disk_info  order by id DESC limit " + str(
 8             (query['pageIndex'] - 1) * query["pageSize"]) + "," + str(query["pageSize"])
 9         count_sql = "select count(*) from disk_info"
10         colume_sql = "select id from disk_info"
11  
12     else:
13         sql1 = "select id,hostname,total,used,available,create_time from mem_info where hostname like '%" + str(query["hostname"]) + "%' order by id DESC" + " limit " + str(
14             (query['pageIndex'] - 1) * query["pageSize"]) + "," + str(query["pageSize"])
15         count_sql = "select count(*) from disk_info where hostname like '%" + str(
16             query["hostname"]) + "%' order by id DESC"
17         colume_sql = "select id from disk_info"
18  
19     sql2 = "select id,hostname,total,used,available,create_time from disk_info"
20     db = conndb()
21     listdata = db.get_data(sql1, sql2)
22     db = conndb()
23     result = db.get_data(count_sql, colume_sql)
24     print(result)
25     pageTotal = result[0]['id']
26     print(listdata)
27     print(pageTotal)
28     data = {'listdata': listdata, "pageTotal": pageTotal, "code": 200}
29     return json.dumps(data)

 

Part4:页面展示

 

 

欢迎关注【无量测试之道】公众号,回复【领取资源】

Python+Unittest框架API自动化、

Python+Unittest框架API自动化、

Python+Pytest框架API自动化、

Python+Pandas+Pyecharts大数据分析、

Python+Selenium框架Web的UI自动化、

Python+Appium框架APP的UI自动化、

Python编程学习资源干货、

资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。

备注:我的个人公众号已正式开通,致力于IT互联网技术的分享。

包含:数据分析、大数据、机器学习、测试开发、API接口自动化、测试运维、UI自动化、性能测试、代码检测、编程技术等。

微信搜索公众号:“无量测试之道”,或扫描下方二维码:

添加关注,让我们一起共同成长!

posted on 2022-01-07 15:17  Wu_Candy  阅读(91)  评论(0编辑  收藏  举报