后台添加数据可视化页面 模型调用次数

This commit is contained in:
Kakune55 2023-12-28 21:55:32 +08:00
parent d6dffde18f
commit 4a809254cd
6 changed files with 175 additions and 9 deletions

52
db.py
View File

@ -55,7 +55,7 @@ def userSurplus(userkey): #查询userkey剩余配额
cursor = db.cursor() cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = ?;",[userkey]) cursor.execute("SELECT surplus FROM usersurplus WHERE userkey = ?;",[userkey])
# 使用 fetchone() 方法获取单条数据. # 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone() data = cursor.fetchone()
@ -73,7 +73,7 @@ def reduce_value(userkey, value): # 减去对应的值
cursor = db.cursor() cursor = db.cursor()
# 执行 SQL 查询以获取当前值 # 执行 SQL 查询以获取当前值
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = ?;",[userkey]) cursor.execute("SELECT surplus FROM usersurplus WHERE userkey = ?;",[userkey])
current_value = cursor.fetchone()[0] current_value = cursor.fetchone()[0]
# 如果没有找到用户,则返回错误信息 # 如果没有找到用户,则返回错误信息
@ -85,7 +85,7 @@ def reduce_value(userkey, value): # 减去对应的值
new_value = current_value - value new_value = current_value - value
# 更新数据库中的值 # 更新数据库中的值
cursor.execute(f"UPDATE usersurplus SET surplus= ? WHERE userkey= ?;",[new_value,userkey]) cursor.execute("UPDATE usersurplus SET surplus= ? WHERE userkey= ?;",[new_value,userkey])
# 提交事务 # 提交事务
db.commit() db.commit()
@ -103,7 +103,7 @@ def getAllKey():
cursor = db.cursor() cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
cursor.execute(f"SELECT * FROM usersurplus ;") cursor.execute("SELECT * FROM usersurplus ;")
# 使用 fetchall() 方法获取结果集 # 使用 fetchall() 方法获取结果集
data = cursor.fetchall() data = cursor.fetchall()
@ -120,7 +120,7 @@ def delKey(userkey):
cursor = db.cursor() cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
cursor.execute(f"DELETE FROM usersurplus WHERE userkey = ?;", [userkey]) cursor.execute("DELETE FROM usersurplus WHERE userkey = ?;", [userkey])
# 提交事务 # 提交事务
db.commit() db.commit()
@ -145,9 +145,9 @@ def createKey(quota,number=1,key="null"):
for i in range(int(number)): for i in range(int(number)):
key = str(uuid.uuid1()) key = str(uuid.uuid1())
output.append(key) output.append(key)
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (?, ?);", [key, quota]) cursor.execute("INSERT INTO usersurplus (userkey,surplus) VALUES (?, ?);", [key, quota])
else: else:
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (?, ?);", [key, quota]) cursor.execute("INSERT INTO usersurplus (userkey,surplus) VALUES (?, ?);", [key, quota])
output.append(key) output.append(key)
@ -167,7 +167,7 @@ def newLog(ip:str, time:int, tokens:int, model:str, userkey:str):
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
cursor.execute(f"INSERT INTO log (ip, time, tokens, model, userkey) VALUES (?, ?, ?, ?, ?);", [ip, time, tokens, model, userkey]) cursor.execute("INSERT INTO log (ip, time, tokens, model, userkey) VALUES (?, ?, ?, ?, ?);", [ip, time, tokens, model, userkey])
# 提交事务 # 提交事务
db.commit() db.commit()
@ -182,7 +182,7 @@ def getlog(num:int):
cursor = db.cursor() cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
cursor.execute(f"SELECT * FROM log order by time desc limit ?;", [num]) cursor.execute("SELECT * FROM log order by time desc limit ?;", [num])
# 使用 fetchall() 方法获取结果集 # 使用 fetchall() 方法获取结果集
data = cursor.fetchall() data = cursor.fetchall()
@ -190,3 +190,37 @@ def getlog(num:int):
db.close() db.close()
return data return data
def getLogAllModel():
#打开数据库连接
db = getconn()
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT DISTINCT model FROM log ;")
# 使用 fetchall() 方法获取结果集
data = cursor.fetchall()
# 关闭连接
db.close()
return data
def countLog(key:str, value:str):
#打开数据库连接
db = getconn()
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
try:
# 使用 execute() 方法执行 SQL 查询
cursor.execute(f"SELECT COUNT(*) FROM log WHERE {key} = ?;", [value])
# 使用 fetchone() 方法获取结果
data = cursor.fetchone()
# 关闭连接
db.close()
except Exception as e:
return e
return data[0]

7
log.py
View File

@ -1,3 +1,4 @@
import json
import time as times import time as times
import db import db
@ -16,4 +17,10 @@ def getlog(num:int):
return data return data
def modelChartsData(): #按模型用量统计
data = []
model = db.getLogAllModel()
for item in model:
data.append({'value':db.countLog("model",item[0]),'name':item[0]})
return data

View File

@ -85,6 +85,13 @@ def adminList():
return flask.render_template("keylist.html",data=data) return flask.render_template("keylist.html",data=data)
return flask.redirect('login') return flask.redirect('login')
@app.route('/api/modelcount')
def apiModelCount():
if "admin" in flask.session :
data = log.modelChartsData()
return data
return flask.abort(403)
@app.route('/admin/log', methods=['GET']) @app.route('/admin/log', methods=['GET'])
def adminListLog(): def adminListLog():
if "admin" in flask.session : if "admin" in flask.session :

45
static/echarts.min.js vendored Normal file

File diff suppressed because one or more lines are too long

68
templates/Echarts.html Normal file
View File

@ -0,0 +1,68 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<script src="../static/echarts.min.js"></script>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: #f7f7f7;
padding: 20px;
}
</style>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
const apiURL = '/api/modelcount';
datajson = null
// 基于准备好的dom初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
//使用fetch API发送GET请求
fetch(apiURL)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 确保返回的是JSON对象
})
.then(data => {
// 确保 data 是一个数组并且每个元素都有 value name 属性
if (data && Array.isArray(data) && data.every(item => item.value && item.name)) {
myChart.setOption({
title: {
text: '模型调用',
left: 'center',
top: 'center',
textStyle:{
fontSize: '25',
fontWeight:'bold'
}
},
series: [{
name: '模型调用',
type: 'pie',
radius: '55%',
data: data,
radius: ['30%', '65%'],
label: {
show: true, //开启显示
fontSize: '16',
formatter: '{b}:{c}' + '\n\r' + '({d}%)',
fontWeight:'bold'
}
}]
});
} else {
console.error('Data received is not in the correct format for ECharts pie chart:', data);
}
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
</script>
</body>
</html>

View File

@ -49,6 +49,11 @@
</head> </head>
<body> <body>
<div class="container">
<h2>概况</h2>
{% include 'Echarts.html' %}
</div>
<hr/>
<div class="container"> <div class="container">
<h2>状态</h2> <h2>状态</h2>
<table> <table>