Test and development: Python + Flask implements the interface to receive Disk information

Posted by writer on Sat, 25 Dec 2021 11:39:17 +0100

Today's sharing is based on: Test Development: Python + Flask implementation interface receives memory information to further share how to use Python + Flask implementation to receive Disk information.

Principle:

Call the Shell script through Python to execute the Disk related commands, then process them, and then request the Requests library to push data to the interface defined at the back end.

Part1: collection end

import os
import requests
import json
import time

url="http://10.8.31.61:5555/GetDiskResource"
mem_data={}
mem_cmd = [
"df -h |grep home |awk -F' ' '{print $2}'",
"df -h |grep home |awk -F' ' '{print $3}'",
"df -h |grep home |awk -F' ' '{print $4}'"
]
def exec_cmd():
    for cmd in mem_cmd:
        print(cmd)
        response = os.popen(cmd)
        if("$2" in cmd):
            mem_data['total']=str(response.read()).replace("\n","")
        elif("$3" in cmd):
            mem_data['used']=str(response.read()).replace("\n","")
        elif("$4" in cmd):
            mem_data['available']=str(response.read()).replace("\n","")
    else:
        mem_data['hostname']=str(os.popen("hostname |awk -F'.' '{print $1}' |awk -F'-' '{print $2}'").read()).replace("\n","")
    response.close()

def httpPost(datas):
    header = {"Content-Type":"application/json"}
    resp_content = requests.post(url=url,data=json.dumps(datas),headers=header)
    print(resp_content.text)

if __name__ == '__main__':
    while True:
        exec_cmd()
        httpPost(mem_data)
        time.sleep(3600)

Part2: receiving end

#Disk routing processing-------------------------------------------------------
@resource.route('/GetDiskResource',methods=['POST'])
def GetDiskResource():
    '''Receive from linux Uploaded data'''
    query = request.get_json()
    hostname = query["hostname"]
    total = query["total"]
    used = query["used"]
    available = query["available"]
    createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    sql = "insert into disk_info (hostname,total,used,available,create_time) VALUES "
    data = "('" + hostname + "','" + total + "','" + used + "','" + available +  "','" + str(createtime) + "'"
    end = data + ")"
    sql = sql + end
    print(sql)
    db = conndb()
    db.execute_sql(sql)
    data = {'code': 200, 'message': 'success', 'status': '10000'}
    return json.dumps(data)

Part 3: display end

This part is mainly divided into the following two parts:

The first is the page request

<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> Disk information
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.hostname" placeholder="environment" class="handle-input mr10" clearable @clear="clear_name"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">search</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="environment"></el-table-column>
                <el-table-column prop="total" label="in total"></el-table-column>
                <el-table-column prop="used" label="Use out"></el-table-column>
                <el-table-column prop="available" label="available">
                  <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="Creation time"></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: {
    // Get the real data returned by the backend
    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
        })
    },
    // Trigger search button
    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
        })
    },
    // Paging navigation
    handleSizeChange (val) {
      // console.log(val)
      this.$set(this.query, 'pageSize', val)
      // console.log(this.query)
      this.getDiskData()
    },
    // Page turning and page changing trigger
    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>

The second block is back-end request processing

@resource.route('/getDiskList',methods=['POST'])
def getDiskList():
    '''fe Page list data acquisition'''
    query = request.get_json()
    print(query)
    if (query["hostname"] == ""):
        sql1 = "select id,hostname,total,used,available,create_time from disk_info  order by id DESC limit " + str(
            (query['pageIndex'] - 1) * query["pageSize"]) + "," + str(query["pageSize"])
        count_sql = "select count(*) from disk_info"
        colume_sql = "select id from disk_info"

    else:
        sql1 = "select id,hostname,total,used,available,create_time from mem_info where hostname like '%" + str(query["hostname"]) + "%' order by id DESC" + " limit " + str(
            (query['pageIndex'] - 1) * query["pageSize"]) + "," + str(query["pageSize"])
        count_sql = "select count(*) from disk_info where hostname like '%" + str(
            query["hostname"]) + "%' order by id DESC"
        colume_sql = "select id from disk_info"

    sql2 = "select id,hostname,total,used,available,create_time from disk_info"
    db = conndb()
    listdata = db.get_data(sql1, sql2)
    db = conndb()
    result = db.get_data(count_sql, colume_sql)
    print(result)
    pageTotal = result[0]['id']
    print(listdata)
    print(pageTotal)
    data = {'listdata': listdata, "pageTotal": pageTotal, "code": 200}
    return json.dumps(data)

Part 4: page display

Now there is such an opportunity. I invite you to join our software testing learning exchange group: 914172719. Note "csdn". You can discuss and exchange software testing together, learn software testing technology, interview and other aspects of software testing together, and have free live classes to gain more testing skills. Let's advance Python automated testing / test development together, The road to high pay.

Let's give you a word of encouragement: when our ability is insufficient, the first thing to do is internal practice! When our ability is strong enough, we can look outside!

Finally, a supporting learning resource is prepared for you, You can be in the official account: [sad hot note] get a 216 page interview classic document of Software Test Engineer for free. And share the corresponding video learning tutorials for free! The materials include basic knowledge, Linux essentials, Shell, Internet program principle, Mysql database, special topics of packet capturing tools, interface testing tools, advanced testing Python programming, Web automation testing and APP automation Automated testing, interface automation testing, advanced continuous integration testing, test architecture development, test framework, performance testing, security testing, etc.

Haowen recommendation

Job transfer interview, job hopping interview, these interview skills that software testers must know!

Interview experience: move bricks in first tier cities! Another software testing post, 5000 will be satisfied

Interviewer: I've worked for three years and have a preliminary test? I'm afraid your title of software test engineer should be enclosed in double quotation marks

What kind of person is suitable for software testing?

The man who left work on time was promoted before me

The test post changed jobs repeatedly and disappeared

As a test engineer with 1 year working experience, my suggestions before the interview are as follows

"After a year in office, the automation software test hired by high salary was persuaded to quit."

4 months of self-study software testing into Ali! How to move from functional testing to automation... What have I experienced

6000 yuan applied for the training course. Three months later, I successfully "cheated" into Tencent's big factory with a monthly salary of 15000 yuan

Topics: Python Back-end Programmer software testing Flask