程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

測試開發:Python + Flask 實現接口接收 CPU 信息

編輯:Python

今天的內容是基於 測試開發:Python + Flask 實現接口接收內存信息 來進一步分享如何使用 Python + Flask 接收 CPU 的信息。

原理:

通過 Python 調用 Shell 腳本去執行 CPU 的相關信息,然後進行處理再請求 Requests 庫來向後端定義好的接口來推送數據。

Part1:收集端

import os
import requests
import json
import time
url="http://10.8.31.61:5555/GetCpuResource"
cpu_data={}
cpu_cmd = [
"cat /proc/cpuinfo |grep 'processor' |wc -l",
"cat /proc/cpuinfo |grep 'physical id'|sort |uniq |wc -l",
"cat /proc/cpuinfo |grep 'cpu cores'|awk -F' ' '{print $4}' |sort |wc -l",
"uptime |awk -F':' '{print $5}'"
]
def exec_cmd():
for cmd in cpu_cmd:
print(cmd)
response = os.popen(cmd)
if("processor" in cmd):
cpu_data['logic_cpu']=str(response.read()).replace("\n","")
elif("physical" in cmd):
cpu_data['physical_cpu']=str(response.read()).replace("\n","")
elif("cores" in cmd):
cpu_data['cpu_cores']=str(response.read()).replace("\n","")
elif("uptime" in cmd):
cpu_data['cpu_load'] = str(response.read()).replace("\n", "")
if (len(cpu_data['cpu_load']) < 3):
response = os.popen("uptime |awk -F':' '{print $4}'")
cpu_data['cpu_load'] = str(response.read()).replace("\n", "")
else:
cpu_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(cpu_data)
time.sleep(3600)

Part2:接收端

#CPU路由處理
@resource.route('/GetCpuResource',methods=['POST'])
def GetCpuResource():
'''接收來自linux上傳的數據'''
query = request.get_json()
hostname = query["hostname"]
logic_cpu = query["logic_cpu"]
physical_cpu = query["physical_cpu"]
cpu_cores = query["cpu_cores"]
cpu_load = query["cpu_load"]
createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = "insert into cpu_info (hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time) VALUES "
data = "('" + hostname + "','" + logic_cpu + "','" + physical_cpu + "','" + cpu_cores + "','" + cpu_load + "','" + 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)

Part3:展示端

這部分主要分為以下兩塊內容:

第一塊是頁面請求
<template>
<div>
<div class="crumbs">
<el-breadcrumb separator="/">
<el-breadcrumb-item>
<i class="el-icon-lx-cascades"></i> CPU信息
</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="logic_cpu" label="邏輯CPU"></el-table-column>
<el-table-column prop="physical_cpu" label="物理CPU"></el-table-column>
<el-table-column prop="cpu_cores" label="CPU核數"></el-table-column>
<el-table-column prop="cpu_load" width="255" label="CPU負載Avg[1min,5min,15min]"></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: 'InterfaceCpu',
data () {
return {
query: {
hostname: '',
pageIndex: 1,
pageSize: 10
},
tableData: [],
pageTotal: 0
}
},
created () {
this.getMemData()
},
methods: {
// 獲取後端返回的真實數據
getMemData () {
server({url: '/getCpuList', data: this.query, method: 'post'})
.then(response => {
console.log('**********')
console.log(response)
this.tableData = response.listdata
console.log(this.tableData)
this.pageTotal = response.pageTotal || 5
})
},
// 觸發搜索按鈕
handleSearch () {
server({url: '/getCpuList', data: this.query, method: 'post'})
.then(response => {
console.log(response)
this.tableData = response.listdata
console.log(this.tableData)
this.pageTotal = response.pageTotal || 5
})
},
// 分頁導航
handleSizeChange (val) {
// console.log(val)
this.$set(this.query, 'pageSize', val)
// console.log(this.query)
this.getMemData()
},
// 翻頁改變頁碼觸發
handleCurrentChange (val) {
this.$set(this.query, 'pageIndex', val)
this.getMemData()
},
clear_name () {
this.query.hostname = ''
this.getMemData()
},
freeplus(rows){
const free =rows.replace("M","")
// console.log(free)
// console.log(typeof free)
return Number(free) <100 ? 'danger' : 'success'
},
availableplus(rows){
const availabl =rows.replace("M","")
// console.log(free)
// console.log(typeof free)
return Number(availabl) <1000 ? '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>
第二塊是後端請求處理
@resource.route('/getCpuList',methods=['POST'])
def getCpuList():
'''fe的頁面列表數據獲取'''
query = request.get_json()
print(query)
if (query["hostname"] == ""):
sql1 = "select id,hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time from cpu_info order by id DESC limit " + str(
(query['pageIndex'] - 1) * query["pageSize"]) + "," + str(query["pageSize"])
count_sql = "select count(*) from mem_info"
colume_sql = "select id from mem_info"
else:
sql1 = "select id,hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time from cpu_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 cpu_info where hostname like '%" + str(
query["hostname"]) + "%' order by id DESC"
colume_sql = "select id from cpu_info"
sql2 = "select id,hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time from cpu_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)

Part4:頁面展示

end


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved