文章目录
- 引用css和js
- 使用
- html
- javascript
- flask
- mysql
- 参考
引用css和js
Bootstrap-table为这些文件提供了 CDN 的支持,所以不需要下载.js .css文件就可以直接用了,十分方便
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.19.1/dist/bootstrap-table.min.css">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://unpkg.com/bootstrap-table@1.19.1/dist/bootstrap-table.min.js"></script>
<!-- Latest compiled and minified Locales -->
<script src="https://unpkg.com/bootstrap-table@1.19.1/dist/locale/bootstrap-table-zh-CN.min.js"></script>
使用
html
在html上添加一行table。
<table id="table"></table>
javascript
在js里面添加:
// 获取后台数据
function MyupdateTable(evn, col_name) {var xmlhttp = new XMLHttpRequest();var json_rep;xmlhttp.onreadystatechange = function(){if (xmlhttp.readyState == 4 && xmlhttp.status == 200){// var json_rep = xmlhttp.responseText.parseJSON(); json_rep = JSON.parse(xmlhttp.responseText)}}xmlhttp.open("GET","http://9.135.90.225:8090/getAlarmMsg?evn=" + evn + "&&col_name=" + col_name, false);xmlhttp.send();return json_rep;
}function judge_except(val) {if (val == 0) return "是";else return "否";
}
// 将json数据转成obj数组
function transData(json_rep, dataTable) {len = json_rep['len']for (var i = 0; i < len; i++) {dataTable.push({id: json_rep['id'][i],time: json_rep['date'][i],col_name: json_rep['colname'][i],actual: json_rep['actual'][i],scope: json_rep['scope'][i],if_except: judge_except(json_rep['if_except'][i])})}
}
var tke_room_nums_data = []
rep_tke_room_nums = MyupdateTable("tke","room_nums")
transData(rep_tke_room_nums, tke_room_nums_data)
// 对于表单结构、模式进行设置
$('#table').bootstrapTable({search: true,pagination: true, //启动分页striped: true, //设置为 true 会有隔行变色效果cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)pageSize: 6,//初始页记录数sortable: true, //排序pageList: [6,36,72,144], //记录数可选列表smartDisplay: false, //程序自动判断显示分页信息columns: [{field: 'id',title: 'ID'}, {field: 'time',title: '时间'}, {field: 'col_name',title: '参数名'}, {field: 'actual',title: '实际值'},{field: 'scope',title: '预测范围'},{field: 'if_except',title: '是否告警'},],data: tke_room_nums_data
})
flask
在flask里添加这样的py程序
# author:hanhandi
# flask学习网址:https://www.w3cschool.cn/flask/flask_routing.html
# pymsql学习网址:
from flask import Flask, render_template, request, jsonify
import pymysql
import json
import logging
from dbutils.pooled_db import PooledDB
# 导入mylib
import sys
sys.path.append('/var/www/html/NewTest/InternShipProject/my_pylib')
from my_global_logic import adjust_table_name
from my_global_logic import Reverse
from my_sql import SELECTapp = Flask(__name__)# @app.route('/')
# def index():
# return render_template("index.html")# 一些配置参数,需要从json文件中读取
with open("/var/www/html/NewTest/InternShipProject/middle_back_end/backend/param_config/179_frame_param_config.json",'r+') as f:load_dict = json.load(f)mapping_path = load_dict["mapping_path"] # 机房与机器ip映射关系文件db_password = load_dict["db_password"]# 初始化日志记录文件
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(filename = '/var/www/html/NewTest/logfiles/alarm_flask_backend.log', level = logging.WARNING, format = LOG_FORMAT, datefmt = DATE_FORMAT)# 解决跨域问题
@app.after_request
def cors(environ):environ.headers['Access-Control-Allow-Origin']='*'environ.headers['Access-Control-Allow-Method']='*'environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'return environdef getMsg(evn, col_name):table_name = evn + "_" + col_name# 返回结果response_data = {'code': 0, 'msg': 'ok'}# 打开数据库连接db = pymysql.connect(host='localhost',user='root',password=db_password,database='alarm_msg')# 使用 cursor() 方法创建一个游标对象 cursorcursor = db.cursor()try:select_sql = "SELECT id, order_date, col_name, actual, scope_left, scope_right, if_except FROM %s order by id desc" % table_nameresult = SELECT(db, cursor, select_sql)id = []date = []colname = []actual = []scope_left = []scope_right = []scope = []if_except = []for row in result:id.append(row[0])date.append(row[1])colname.append(row[2])actual.append(row[3])scope_left.append(row[4])scope_right.append(row[5])if_except.append(row[6])for i in range(len(scope_left)):scope.append("[" + str(scope_left[i]) + ", "+ str(scope_right[i]) + "]")# 关闭数据库连接cursor.close()db.close()response_data['len'] = len(id)response_data['id'] = idresponse_data['date'] = dateresponse_data['colname'] = colnameresponse_data['actual'] = actualresponse_data['scope'] = scoperesponse_data['if_except'] = if_exceptreturn json.dumps(response_data, default=str) except BaseException:logging.critical("Function: getMsg stop ...")cursor.close()db.close()return json.dumps(response_data) @app.route('/getAlarmMsg', methods=['GET'])
def getAlarmMsg():try:evn = request.args['evn']col_name = request.args['col_name']return getMsg(evn, col_name)except BaseException:response_data = {'code': 0, 'msg': 'error'}return json.dumps(response_data) if __name__ == '__main__': try: app.run(host='0.0.0.0', port=8090, debug=True)except BaseException:logging.critical("app stop ...")
mysql
mysql里面的表单存储结构为:
mysql> use alarm_msg;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -ADatabase changed
mysql> show tables;
+---------------------+
| Tables_in_alarm_msg |
+---------------------+
| cvm_flow_down |
| cvm_flow_up |
| cvm_room_nums |
| cvm_user_nums |
| tke_flow_down |
| tke_flow_up |
| tke_room_nums |
| tke_user_nums |
+---------------------+
8 rows in set (0.00 sec)mysql> select * from cvm_flow_down;
+-----+---------------------+----------+-----------+------------+------------+-------------+-----------+
| id | order_date | today_id | col_name | actual | scope_left | scope_right | if_except |
+-----+---------------------+----------+-----------+------------+------------+-------------+-----------+
| 1 | 2022-03-14 18:20:43 | 110 | flow_down | 392615039 | -628001 | 336556517 | 1 |
| 2 | 2022-03-14 18:30:42 | 111 | flow_down | 409642229 | 746497 | 383903533 | 1 |
| 3 | 2022-03-14 18:40:41 | 112 | flow_down | 526891185 | 4350006 | 419925905 | 1 |
| 4 | 2022-03-14 18:50:39 | 113 | flow_down | 557464437 | 10199705 | 451904363 | 1 |
| 5 | 2022-03-14 19:00:48 | 114 | flow_down | 648641400 | 22094813 | 481082273 | 1 |
| 6 | 2022-03-14 19:10:45 | 115 | flow_down | 884153264 | 36335606 | 502285379 | 1 |
最后结果:
参考
https://v3.bootcss.com/getting-started/
https://bootstrap-table.com/docs/getting-started/download/