|
|
@ -1,49 +1,54 @@
|
|
|
|
import math
|
|
|
|
import math
|
|
|
|
import random
|
|
|
|
import random
|
|
|
|
import psutil
|
|
|
|
import psutil ##使用psutil库获取系统和进程信息
|
|
|
|
import pymysql
|
|
|
|
import pymysql ##提供Mysql数据库接口
|
|
|
|
import pytz
|
|
|
|
import pytz
|
|
|
|
|
|
|
|
import datetime ##pytz库配合datetime,用于创建本地时间,设置时间戳
|
|
|
|
|
|
|
|
from flask import Flask, render_template, jsonify, request, session, redirect, url_for ##导入flask库包括 Flask 主类、用于渲染模板和处理 JSON 的模块,会话管理 session,重定向 redirect,以及日期时间处理 datetime。
|
|
|
|
|
|
|
|
|
|
|
|
from flask import Flask, render_template, jsonify, request, session, redirect, url_for
|
|
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
from sqlalchemy.sql.ddl import CreateTable
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
##创建flask应用实例
|
|
|
|
app = Flask(__name__)
|
|
|
|
app = Flask(__name__)
|
|
|
|
# 创建数据库连接
|
|
|
|
app.secret_key = 'SecretKey' #设置flask密钥,提高安全性
|
|
|
|
app.secret_key = 'SecretKey' # 设置Secret Key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/404") #host:post/404:404页面展示,主要用于划分权限查看
|
|
|
|
|
|
|
|
|
|
|
|
##定义各种路由,以及对应的视图函数,用于处理不同页面的请求和访问
|
|
|
|
|
|
|
|
####非管理者查看数据会显示404页面
|
|
|
|
|
|
|
|
@app.route("/404")
|
|
|
|
def index_404():
|
|
|
|
def index_404():
|
|
|
|
return render_template('page/404.html',)
|
|
|
|
return render_template('page/404.html',)
|
|
|
|
|
|
|
|
|
|
|
|
##注销页面
|
|
|
|
####用户注销,重定向到登陆页面,重新登陆
|
|
|
|
@app.route("/logout") #host:post/logout:
|
|
|
|
@app.route("/logout")
|
|
|
|
def logout():
|
|
|
|
def logout():
|
|
|
|
session.clear() # 清除会话数据
|
|
|
|
session.clear() # 清除会话数据
|
|
|
|
# session['logged_out'] = True
|
|
|
|
# session['logged_out'] = True
|
|
|
|
return redirect(url_for('login'))
|
|
|
|
return redirect(url_for('login'))
|
|
|
|
##注册页面
|
|
|
|
|
|
|
|
|
|
|
|
####渲染注册界面
|
|
|
|
@app.route("/register")
|
|
|
|
@app.route("/register")
|
|
|
|
def register():
|
|
|
|
def register():
|
|
|
|
return render_template('page/register.html',)
|
|
|
|
return render_template('page/register.html',)
|
|
|
|
##登录页面
|
|
|
|
|
|
|
|
|
|
|
|
####渲染登录界面
|
|
|
|
@app.route("/login")
|
|
|
|
@app.route("/login")
|
|
|
|
def login():
|
|
|
|
def login():
|
|
|
|
return render_template('page/login.html',)
|
|
|
|
return render_template('page/login.html',)
|
|
|
|
##登录接口,通过Ajax实现异步交互
|
|
|
|
|
|
|
|
|
|
|
|
####API路由,使用GET方法同步登录请求
|
|
|
|
@app.route("/api_login", methods=['GET'])
|
|
|
|
@app.route("/api_login", methods=['GET'])
|
|
|
|
def api_login():
|
|
|
|
def api_login():
|
|
|
|
username =request.args.get('username')
|
|
|
|
username =request.args.get('username')
|
|
|
|
password = request.args.get('password')
|
|
|
|
password = request.args.get('password')
|
|
|
|
# 连接到数据库
|
|
|
|
######连接到MySQL数据库
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
# 检查用户名和密码是否正确
|
|
|
|
###### SQL查询相匹配用户
|
|
|
|
sql = f"SELECT * FROM user WHERE username = '{username}' AND password = '{password}'"
|
|
|
|
sql = f"SELECT * FROM user WHERE username = '{username}' AND password = '{password}'"
|
|
|
|
cursor.execute(sql)
|
|
|
|
cursor.execute(sql)
|
|
|
|
result = cursor.fetchone()
|
|
|
|
result = cursor.fetchone()
|
|
|
|
|
|
|
|
######设置会话数据
|
|
|
|
if result:
|
|
|
|
if result:
|
|
|
|
session['quanxian'] = result['quanxian']
|
|
|
|
session['quanxian'] = result['quanxian']
|
|
|
|
session['username'] = username
|
|
|
|
session['username'] = username
|
|
|
@ -51,29 +56,27 @@ def api_login():
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
data = {'code': 1, 'msg': '登录失败'}
|
|
|
|
data = {'code': 1, 'msg': '登录失败'}
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
connection.close() # 确保数据库连接被关闭
|
|
|
|
connection.close()
|
|
|
|
return jsonify(data)
|
|
|
|
return jsonify(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
####API路由,同步处理注册请求
|
|
|
|
@app.route("/api_register", methods=['GET'])
|
|
|
|
@app.route("/api_register", methods=['GET'])
|
|
|
|
def api_register():
|
|
|
|
def api_register():
|
|
|
|
username =request.args.get('username')
|
|
|
|
username =request.args.get('username')
|
|
|
|
password = request.args.get('password')
|
|
|
|
password = request.args.get('password')
|
|
|
|
# 连接到数据库
|
|
|
|
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
# 插入一条数据的 SQL 语句
|
|
|
|
######执行插入操作,添加新用户
|
|
|
|
sql = """
|
|
|
|
sql = """
|
|
|
|
INSERT INTO user(username, password,quanxian)
|
|
|
|
INSERT INTO user(username, password,quanxian)
|
|
|
|
VALUES (%s, %s, %s)
|
|
|
|
VALUES (%s, %s, %s)
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
# 替换 %s 为你想要插入的数据
|
|
|
|
######数据格式:【用户名,密码,用户权限(默认0)】
|
|
|
|
data = (username,password,0)
|
|
|
|
data = (username,password,0)
|
|
|
|
# 执行 SQL 语句
|
|
|
|
|
|
|
|
cursor.execute(sql, data)
|
|
|
|
cursor.execute(sql, data)
|
|
|
|
# 提交事务
|
|
|
|
|
|
|
|
connection.commit()
|
|
|
|
connection.commit()
|
|
|
|
|
|
|
|
#######返回信息
|
|
|
|
res_data = {
|
|
|
|
res_data = {
|
|
|
|
'code': 0,
|
|
|
|
'code': 0,
|
|
|
|
'msg': '注册成功'
|
|
|
|
'msg': '注册成功'
|
|
|
@ -84,25 +87,28 @@ def api_register():
|
|
|
|
'msg': '注册失败'
|
|
|
|
'msg': '注册失败'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
connection.close() # 确保数据库连接被关闭
|
|
|
|
connection.close()
|
|
|
|
|
|
|
|
|
|
|
|
return jsonify(res_data)
|
|
|
|
return jsonify(res_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###定义默认登录界面
|
|
|
|
@app.route("/")
|
|
|
|
@app.route("/")
|
|
|
|
def logins():
|
|
|
|
def logins():
|
|
|
|
return render_template('page/login.html',)
|
|
|
|
return render_template('page/login.html',)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###定义主页面
|
|
|
|
@app.route("/index_echarts")
|
|
|
|
@app.route("/index_echarts")
|
|
|
|
def index_echarts():
|
|
|
|
def index_echarts():
|
|
|
|
return render_template('index.html',)
|
|
|
|
return render_template('index.html',)
|
|
|
|
##告警
|
|
|
|
|
|
|
|
|
|
|
|
###检查用户的权限,如果是管理员(权限为1),返回告警页面,否则返回404页面
|
|
|
|
@app.route("/warings")
|
|
|
|
@app.route("/warings")
|
|
|
|
def warings():
|
|
|
|
def warings():
|
|
|
|
if session['quanxian'] == 1:
|
|
|
|
if session['quanxian'] == 1:
|
|
|
|
return render_template('page/warings.html')
|
|
|
|
return render_template('page/warings.html')
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
return render_template('page/404.html')
|
|
|
|
return render_template('page/404.html')
|
|
|
|
##管理员权限
|
|
|
|
|
|
|
|
|
|
|
|
###管理员页面
|
|
|
|
@app.route("/admin")
|
|
|
|
@app.route("/admin")
|
|
|
|
def admin():
|
|
|
|
def admin():
|
|
|
|
username = session['username']
|
|
|
|
username = session['username']
|
|
|
@ -111,10 +117,12 @@ def admin():
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return render_template('page/index.html', **data)
|
|
|
|
return render_template('page/index.html', **data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###日志界面
|
|
|
|
@app.route("/log")
|
|
|
|
@app.route("/log")
|
|
|
|
def log():
|
|
|
|
def log():
|
|
|
|
return render_template('page/table.html',)
|
|
|
|
return render_template('page/table.html',)
|
|
|
|
##用户权限
|
|
|
|
|
|
|
|
|
|
|
|
###用户界面,检查用户的权限,如果是管理员(权限为1),返回用户页面,否则返回404页面
|
|
|
|
@app.route("/user")
|
|
|
|
@app.route("/user")
|
|
|
|
def user():
|
|
|
|
def user():
|
|
|
|
if session['quanxian'] ==1:
|
|
|
|
if session['quanxian'] ==1:
|
|
|
@ -122,12 +130,13 @@ def user():
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
return render_template('page/404.html')
|
|
|
|
return render_template('page/404.html')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###创建数据库表
|
|
|
|
@app.route("/install")
|
|
|
|
@app.route("/install")
|
|
|
|
def install():
|
|
|
|
def install():
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456',database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456',database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
# 创建一个表的 SQL 语句
|
|
|
|
###### 创建表my_table,包含ID、CPU、内存、磁盘、上行、下行、机器号和时间戳字段
|
|
|
|
sql = """
|
|
|
|
sql = """
|
|
|
|
CREATE TABLE IF NOT EXISTS my_table (
|
|
|
|
CREATE TABLE IF NOT EXISTS my_table (
|
|
|
|
ID INT AUTO_INCREMENT PRIMARY KEY,
|
|
|
|
ID INT AUTO_INCREMENT PRIMARY KEY,
|
|
|
@ -140,6 +149,7 @@ def install():
|
|
|
|
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
|
|
|
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
|
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
|
|
|
|
###### 创建表user,包含ID、用户名、密码、权限和时间戳字段
|
|
|
|
user_sql = """
|
|
|
|
user_sql = """
|
|
|
|
CREATE TABLE IF NOT EXISTS user (
|
|
|
|
CREATE TABLE IF NOT EXISTS user (
|
|
|
|
ID INT AUTO_INCREMENT PRIMARY KEY,
|
|
|
|
ID INT AUTO_INCREMENT PRIMARY KEY,
|
|
|
@ -150,6 +160,7 @@ def install():
|
|
|
|
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
|
|
|
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
|
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
|
|
|
|
###### 创建表warings,包含ID、CPU、内存、磁盘、上行、下行、机器号、消息、IP和时间戳字段
|
|
|
|
warings = """
|
|
|
|
warings = """
|
|
|
|
CREATE TABLE IF NOT EXISTS warings (
|
|
|
|
CREATE TABLE IF NOT EXISTS warings (
|
|
|
|
ID INT AUTO_INCREMENT PRIMARY KEY,
|
|
|
|
ID INT AUTO_INCREMENT PRIMARY KEY,
|
|
|
@ -164,43 +175,37 @@ def install():
|
|
|
|
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
|
|
|
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
|
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
# 执行 SQL 语句
|
|
|
|
|
|
|
|
cursor.execute(warings)
|
|
|
|
cursor.execute(warings)
|
|
|
|
# 执行 SQL 语句
|
|
|
|
|
|
|
|
cursor.execute(user_sql)
|
|
|
|
cursor.execute(user_sql)
|
|
|
|
# 执行 SQL 语句
|
|
|
|
|
|
|
|
cursor.execute(sql)
|
|
|
|
cursor.execute(sql)
|
|
|
|
# 提交事务
|
|
|
|
|
|
|
|
db.commit()
|
|
|
|
db.commit()
|
|
|
|
|
|
|
|
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
# 关闭数据库连接
|
|
|
|
|
|
|
|
db.close()
|
|
|
|
db.close()
|
|
|
|
return jsonify({'code':0,'msg':'数据库创建成功'})
|
|
|
|
return jsonify({'code':0,'msg':'数据库创建成功'})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###使用GET方法处理日志分页查询请求
|
|
|
|
@app.route("/api_log", methods=['GET'])
|
|
|
|
@app.route("/api_log", methods=['GET'])
|
|
|
|
def api_log():
|
|
|
|
def api_log():
|
|
|
|
# 假设每页显示10条记录
|
|
|
|
######获取请求参数中的煤业记录数LIMIT_PER_PAGE
|
|
|
|
LIMIT_PER_PAGE =int(request.args.get('limit'))
|
|
|
|
LIMIT_PER_PAGE =int(request.args.get('limit'))
|
|
|
|
# 假设我们要查询第3页的数据
|
|
|
|
######请求参数的当前页数PAGE
|
|
|
|
PAGE = int(request.args.get('page'))
|
|
|
|
PAGE = int(request.args.get('page'))
|
|
|
|
# 计算 OFFSET
|
|
|
|
######计算偏移量OFFSET
|
|
|
|
OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
|
|
|
|
OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
|
|
|
|
# 创建数据库连接
|
|
|
|
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
# 创建一个 SQL 查询,使用 LIMIT 和 OFFSET 进行翻页
|
|
|
|
######创建一个 SQL 查询,使用 LIMIT 和 OFFSET 进行翻页
|
|
|
|
sql = "SELECT * FROM my_table LIMIT %s OFFSET %s"
|
|
|
|
sql = "SELECT * FROM my_table LIMIT %s OFFSET %s"
|
|
|
|
cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
|
|
|
|
cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
|
|
|
|
# 获取所有记录
|
|
|
|
######查询并传递参数
|
|
|
|
results = cursor.fetchall()
|
|
|
|
results = cursor.fetchall()
|
|
|
|
# 创建一个 SQL 查询,用于获取表中的行数
|
|
|
|
|
|
|
|
sql_count = "SELECT COUNT(*) FROM my_table"
|
|
|
|
sql_count = "SELECT COUNT(*) FROM my_table"
|
|
|
|
cursor.execute(sql_count)
|
|
|
|
cursor.execute(sql_count)
|
|
|
|
result_count = cursor.fetchone()
|
|
|
|
result_count = cursor.fetchone()
|
|
|
|
count = result_count['COUNT(*)']
|
|
|
|
count = result_count['COUNT(*)']
|
|
|
|
res=[]
|
|
|
|
res=[]
|
|
|
|
|
|
|
|
######创建结果列表
|
|
|
|
for row in results:
|
|
|
|
for row in results:
|
|
|
|
print(row)
|
|
|
|
print(row)
|
|
|
|
res.append({
|
|
|
|
res.append({
|
|
|
@ -214,36 +219,28 @@ def api_log():
|
|
|
|
'at':row['at']
|
|
|
|
'at':row['at']
|
|
|
|
})
|
|
|
|
})
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
# 关闭数据库连接
|
|
|
|
|
|
|
|
connection.close()
|
|
|
|
connection.close()
|
|
|
|
data={'code':0,'msg':'','count':count,'data':res}
|
|
|
|
data={'code':0,'msg':'','count':count,'data':res}
|
|
|
|
return jsonify(data)
|
|
|
|
return jsonify(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###定义一个API路由,使用GET方法处理告警信息分页查询请求,与api_log相比处理了额外的message字段
|
|
|
|
@app.route("/api_warings", methods=['GET'])
|
|
|
|
@app.route("/api_warings", methods=['GET'])
|
|
|
|
def api_warings():
|
|
|
|
def api_warings():
|
|
|
|
# 设置页面数据量
|
|
|
|
|
|
|
|
LIMIT_PER_PAGE =int(request.args.get('limit'))
|
|
|
|
LIMIT_PER_PAGE =int(request.args.get('limit'))
|
|
|
|
# 查询页面数据
|
|
|
|
|
|
|
|
PAGE = int(request.args.get('page'))
|
|
|
|
PAGE = int(request.args.get('page'))
|
|
|
|
# 计算 OFFSET
|
|
|
|
|
|
|
|
OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
|
|
|
|
OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
|
|
|
|
# 创建数据库连接
|
|
|
|
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
# 创建一个 SQL 查询,使用 LIMIT 和 OFFSET 进行翻页
|
|
|
|
|
|
|
|
sql = "SELECT * FROM warings LIMIT %s OFFSET %s"
|
|
|
|
sql = "SELECT * FROM warings LIMIT %s OFFSET %s"
|
|
|
|
cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
|
|
|
|
cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
|
|
|
|
# 获取所有记录
|
|
|
|
|
|
|
|
results = cursor.fetchall()
|
|
|
|
results = cursor.fetchall()
|
|
|
|
# 创建一个 SQL 查询,用于获取表中的行数
|
|
|
|
|
|
|
|
sql_count = "SELECT COUNT(*) FROM warings"
|
|
|
|
sql_count = "SELECT COUNT(*) FROM warings"
|
|
|
|
cursor.execute(sql_count)
|
|
|
|
cursor.execute(sql_count)
|
|
|
|
result_count = cursor.fetchone()
|
|
|
|
result_count = cursor.fetchone()
|
|
|
|
count = result_count['COUNT(*)']
|
|
|
|
count = result_count['COUNT(*)']
|
|
|
|
res=[]
|
|
|
|
res=[]
|
|
|
|
for row in results:
|
|
|
|
for row in results:
|
|
|
|
|
|
|
|
|
|
|
|
res.append({
|
|
|
|
res.append({
|
|
|
|
'id':row['ID'],
|
|
|
|
'id':row['ID'],
|
|
|
|
'cpu':row['CPU'],
|
|
|
|
'cpu':row['CPU'],
|
|
|
@ -256,57 +253,52 @@ def api_warings():
|
|
|
|
'at':row['at']
|
|
|
|
'at':row['at']
|
|
|
|
})
|
|
|
|
})
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
# 关闭数据库连接
|
|
|
|
|
|
|
|
connection.close()
|
|
|
|
connection.close()
|
|
|
|
data={'code':0,'msg':'','count':count,'data':res}
|
|
|
|
data={'code':0,'msg':'','count':count,'data':res}
|
|
|
|
return jsonify(data)
|
|
|
|
return jsonify(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###使用GET方法处理用户信息分页查询请求
|
|
|
|
@app.route("/api_user", methods=['GET'])
|
|
|
|
@app.route("/api_user", methods=['GET'])
|
|
|
|
def api_user():
|
|
|
|
def api_user():
|
|
|
|
# 假设每页显示10条记录
|
|
|
|
|
|
|
|
LIMIT_PER_PAGE =int(request.args.get('limit'))
|
|
|
|
LIMIT_PER_PAGE =int(request.args.get('limit'))
|
|
|
|
# 假设我们要查询第3页的数据
|
|
|
|
|
|
|
|
PAGE = int(request.args.get('page'))
|
|
|
|
PAGE = int(request.args.get('page'))
|
|
|
|
# 计算 OFFSET
|
|
|
|
|
|
|
|
OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
|
|
|
|
OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
|
|
|
|
# 创建数据库连接
|
|
|
|
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
# 创建一个 SQL 查询,使用 LIMIT 和 OFFSET 进行翻页
|
|
|
|
|
|
|
|
sql = "SELECT * FROM user LIMIT %s OFFSET %s"
|
|
|
|
sql = "SELECT * FROM user LIMIT %s OFFSET %s"
|
|
|
|
cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
|
|
|
|
cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
|
|
|
|
# 获取所有记录
|
|
|
|
|
|
|
|
results = cursor.fetchall()
|
|
|
|
results = cursor.fetchall()
|
|
|
|
# 创建一个 SQL 查询,用于获取表中的行数
|
|
|
|
|
|
|
|
sql_count = "SELECT COUNT(*) FROM user"
|
|
|
|
sql_count = "SELECT COUNT(*) FROM user"
|
|
|
|
cursor.execute(sql_count)
|
|
|
|
cursor.execute(sql_count)
|
|
|
|
result_count = cursor.fetchone()
|
|
|
|
result_count = cursor.fetchone()
|
|
|
|
count = result_count['COUNT(*)']
|
|
|
|
count = result_count['COUNT(*)']
|
|
|
|
res=[]
|
|
|
|
res=[]
|
|
|
|
|
|
|
|
######根据用户权限字段,设置权限描述:quanxian==0为普通用户,quanxian==1为管理员
|
|
|
|
for row in results:
|
|
|
|
for row in results:
|
|
|
|
if row['quanxian']==0:
|
|
|
|
if row['quanxian']==0:
|
|
|
|
quanxian='普通用户'
|
|
|
|
quanxian='普通用户'
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
|
|
|
|
|
|
|
|
quanxian = '超级管理员'
|
|
|
|
quanxian = '超级管理员'
|
|
|
|
res.append({
|
|
|
|
res.append({
|
|
|
|
'id':row['ID'],
|
|
|
|
'id':row['ID'],
|
|
|
|
'username':row['username'],
|
|
|
|
'username':row['username'],
|
|
|
|
'quanxian':quanxian,
|
|
|
|
'quanxian':quanxian,
|
|
|
|
|
|
|
|
|
|
|
|
'at':row['at']
|
|
|
|
'at':row['at']
|
|
|
|
})
|
|
|
|
})
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
# 关闭数据库连接
|
|
|
|
|
|
|
|
connection.close()
|
|
|
|
connection.close()
|
|
|
|
data={'code':0,'msg':'','count':count,'data':res}
|
|
|
|
data={'code':0,'msg':'','count':count,'data':res}
|
|
|
|
return jsonify(data)
|
|
|
|
return jsonify(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###使用GET方法处理系统资源使用情况查询请求
|
|
|
|
@app.route("/api_msg")
|
|
|
|
@app.route("/api_msg")
|
|
|
|
def api_msg():
|
|
|
|
def api_msg():
|
|
|
|
|
|
|
|
###### 获取内存使用情况
|
|
|
|
total_mem,used_mem,available_memory_gb,memory_percent=neicun()
|
|
|
|
total_mem,used_mem,available_memory_gb,memory_percent=neicun()
|
|
|
|
|
|
|
|
###### 获取CPU使用率
|
|
|
|
cpu=get_cpu_percent()
|
|
|
|
cpu=get_cpu_percent()
|
|
|
|
|
|
|
|
###### 获取磁盘使用情况
|
|
|
|
used, free,usage_percent= get_disk_usage()
|
|
|
|
used, free,usage_percent= get_disk_usage()
|
|
|
|
disk_data=[
|
|
|
|
disk_data=[
|
|
|
|
{
|
|
|
|
{
|
|
|
@ -345,35 +337,30 @@ def api_msg():
|
|
|
|
'name':'未用内存',
|
|
|
|
'name':'未用内存',
|
|
|
|
'value':available_memory_gb
|
|
|
|
'value':available_memory_gb
|
|
|
|
}]
|
|
|
|
}]
|
|
|
|
|
|
|
|
######插入数据到数据库
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456',database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456',database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
# 插入一条数据的 SQL 语句
|
|
|
|
|
|
|
|
sql = """
|
|
|
|
sql = """
|
|
|
|
INSERT INTO my_table(CPU, neicun, disk, shang, xia, jiqihao)
|
|
|
|
INSERT INTO my_table(CPU, neicun, disk, shang, xia, jiqihao)
|
|
|
|
VALUES (%s, %s, %s, %s, %s, %s)
|
|
|
|
VALUES (%s, %s, %s, %s, %s, %s)
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
data = (int(cpu), memory_percent, usage_percent,shang, xia, '业务2号机')
|
|
|
|
data = (int(cpu), memory_percent, usage_percent,shang, xia, '业务2号机')
|
|
|
|
cursor.execute(sql, data)
|
|
|
|
cursor.execute(sql, data)
|
|
|
|
# 执行 SQL 语句
|
|
|
|
######实现告警,这里设置的是CPU负载高于90%,插入到waring表
|
|
|
|
if 100-int(cpu)>=90:
|
|
|
|
if 100-int(cpu)>=90:
|
|
|
|
sql = """
|
|
|
|
sql = """
|
|
|
|
INSERT INTO warings(CPU, neicun, disk, shang, xia, jiqihao,message)
|
|
|
|
INSERT INTO warings(CPU, neicun, disk, shang, xia, jiqihao,message)
|
|
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
|
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
# 替换 %s 为你想要插入的数据
|
|
|
|
|
|
|
|
data = (int(cpu), memory_percent, usage_percent, shang, xia, '业务2号机','CPU负载过高')
|
|
|
|
data = (int(cpu), memory_percent, usage_percent, shang, xia, '业务2号机','CPU负载过高')
|
|
|
|
cursor.execute(sql, data)
|
|
|
|
cursor.execute(sql, data)
|
|
|
|
db.commit()
|
|
|
|
db.commit()
|
|
|
|
|
|
|
|
|
|
|
|
print("数据插入成功!")
|
|
|
|
print("数据插入成功!")
|
|
|
|
|
|
|
|
######捕获并打印数据库操作中任何错误
|
|
|
|
except pymysql.MySQLError as e:
|
|
|
|
except pymysql.MySQLError as e:
|
|
|
|
print(f"发生错误: {e}")
|
|
|
|
print(f"发生错误: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
# 关闭连接
|
|
|
|
|
|
|
|
db.close()
|
|
|
|
db.close()
|
|
|
|
data={
|
|
|
|
data={
|
|
|
|
'neicun':neicun_data,
|
|
|
|
'neicun':neicun_data,
|
|
|
@ -383,44 +370,39 @@ def api_msg():
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return jsonify(data)
|
|
|
|
return jsonify(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###删除用户
|
|
|
|
@app.route("/delete_username", methods=['GET'])
|
|
|
|
@app.route("/delete_username", methods=['GET'])
|
|
|
|
def delete_username():
|
|
|
|
def delete_username():
|
|
|
|
# 假设每页显示10条记录,通过设置最大单词读取数,优化数据库性能
|
|
|
|
|
|
|
|
id =request.args.get('id')
|
|
|
|
id =request.args.get('id')
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
# 插入一条数据的 SQL 语句
|
|
|
|
|
|
|
|
sql = f"DELETE FROM user WHERE id = '{id}'"
|
|
|
|
sql = f"DELETE FROM user WHERE id = '{id}'"
|
|
|
|
|
|
|
|
|
|
|
|
cursor.execute(sql)
|
|
|
|
cursor.execute(sql)
|
|
|
|
db.commit()
|
|
|
|
db.commit()
|
|
|
|
data={
|
|
|
|
data={
|
|
|
|
'code':0,
|
|
|
|
'code':0,
|
|
|
|
'msg':'用户删除成功'
|
|
|
|
'msg':'用户删除成功'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
except pymysql.MySQLError as e:
|
|
|
|
except pymysql.MySQLError as e:
|
|
|
|
print(f"发生错误: {e}")
|
|
|
|
print(f"发生错误: {e}")
|
|
|
|
data = {
|
|
|
|
data = {
|
|
|
|
'code': 1,
|
|
|
|
'code': 1,
|
|
|
|
'msg': f'发生错误: {e}'
|
|
|
|
'msg': f'发生错误: {e}'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
finally:
|
|
|
|
finally:
|
|
|
|
# 关闭连接
|
|
|
|
|
|
|
|
db.close()
|
|
|
|
db.close()
|
|
|
|
return jsonify(data)
|
|
|
|
return jsonify(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###设置超级管理员
|
|
|
|
@app.route("/api_Superadmin", methods=['GET'])
|
|
|
|
@app.route("/api_Superadmin", methods=['GET'])
|
|
|
|
def api_Superadmin():
|
|
|
|
def api_Superadmin():
|
|
|
|
# 假设每页显示10条记录
|
|
|
|
######通过GET请求参数获取要设置超级管理员的用户ID
|
|
|
|
id =request.args.get('id')
|
|
|
|
id =request.args.get('id')
|
|
|
|
|
|
|
|
######尝试连接数据库并更新对应ID的用户权限
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
with db.cursor() as cursor:
|
|
|
|
# 插入一条数据的 SQL 语句
|
|
|
|
|
|
|
|
sql = f"UPDATE user SET quanxian = 1 WHERE id = '{id}'"
|
|
|
|
sql = f"UPDATE user SET quanxian = 1 WHERE id = '{id}'"
|
|
|
|
cursor.execute(sql)
|
|
|
|
cursor.execute(sql)
|
|
|
|
db.commit()
|
|
|
|
db.commit()
|
|
|
@ -428,7 +410,6 @@ def api_Superadmin():
|
|
|
|
'code':0,
|
|
|
|
'code':0,
|
|
|
|
'msg':'用户设置成功'
|
|
|
|
'msg':'用户设置成功'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
except pymysql.MySQLError as e:
|
|
|
|
except pymysql.MySQLError as e:
|
|
|
|
data = {
|
|
|
|
data = {
|
|
|
|
'code': 1,
|
|
|
|
'code': 1,
|
|
|
@ -439,28 +420,35 @@ def api_Superadmin():
|
|
|
|
db.close()
|
|
|
|
db.close()
|
|
|
|
return jsonify(data)
|
|
|
|
return jsonify(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
###获取资源使用情况的函数,主要借助psutil库
|
|
|
|
|
|
|
|
####获取内存总量、已用内存、可用内存和内存使用百分比。
|
|
|
|
def neicun():
|
|
|
|
def neicun():
|
|
|
|
# 获取内存信息
|
|
|
|
###### 获取内存信息
|
|
|
|
mem = psutil.virtual_memory()
|
|
|
|
mem = psutil.virtual_memory()
|
|
|
|
# 将字节转换为GB
|
|
|
|
###### 将字节转换为GB
|
|
|
|
total_memory_gb = mem.total / (1024 ** 3)
|
|
|
|
total_memory_gb = mem.total / (1024 ** 3)
|
|
|
|
used_memory_gb = mem.used / (1024 ** 3)
|
|
|
|
used_memory_gb = mem.used / (1024 ** 3)
|
|
|
|
available_memory_gb = mem.available / (1024 ** 3) # 空闲内存
|
|
|
|
available_memory_gb = mem.available / (1024 ** 3) # 空闲内存
|
|
|
|
# 计算空间占比(已用内存占总内存的百分比)
|
|
|
|
###### 计算空间占比(已用内存占总内存的百分比)
|
|
|
|
memory_percent = (mem.used / mem.total) * 100
|
|
|
|
memory_percent = (mem.used / mem.total) * 100
|
|
|
|
return total_memory_gb,used_memory_gb,available_memory_gb,memory_percent
|
|
|
|
return total_memory_gb,used_memory_gb,available_memory_gb,memory_percent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
####获取CPU使用百分比
|
|
|
|
def get_cpu_percent(interval=1):
|
|
|
|
def get_cpu_percent(interval=1):
|
|
|
|
return psutil.cpu_percent(interval=interval)
|
|
|
|
return psutil.cpu_percent(interval=interval)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
####获取磁盘已用空间、未用空间、总空间和使用百分比
|
|
|
|
def get_disk_usage(disk_path='/'):
|
|
|
|
def get_disk_usage(disk_path='/'):
|
|
|
|
disk_usage = psutil.disk_usage(disk_path)
|
|
|
|
disk_usage = psutil.disk_usage(disk_path)
|
|
|
|
used = disk_usage.used # 已用空间
|
|
|
|
used = disk_usage.used
|
|
|
|
free = disk_usage.free # 未用空间
|
|
|
|
free = disk_usage.free
|
|
|
|
total = disk_usage.total
|
|
|
|
total = disk_usage.total
|
|
|
|
|
|
|
|
######计算已用空间与总空间的比例(以百分比表示)
|
|
|
|
# 计算已用空间与总空间的比例(以百分比表示)
|
|
|
|
|
|
|
|
usage_percent = (used / total) * 100
|
|
|
|
usage_percent = (used / total) * 100
|
|
|
|
return used, free,usage_percent
|
|
|
|
return used, free,usage_percent
|
|
|
|
|
|
|
|
|
|
|
|
##设置URL
|
|
|
|
|
|
|
|
|
|
|
|
###启动Flask应用程序,在本地开发环境中运行,监听127.0.0.1地址上的7000端口
|
|
|
|
if __name__ == '__main__':
|
|
|
|
if __name__ == '__main__':
|
|
|
|
app.run(debug=True, host='127.0.0.1', port='7000')
|
|
|
|
app.run(debug=True, host='127.0.0.1', port='7000')
|
|
|
|