Python课设-学生信息管理系统
青梅煮酒与君饮 2024-07-30 09:35:05 阅读 82
一、效果展示图
二、前端代码
1、HTML代码
<1>index.html
<code><!DOCTYPE html>
<html lang="en">code>
<head>
<meta charset="UTF-8">code>
<meta name="viewport" content="width=device-width, initial-scale=1.0">code>
<meta http-equiv="X-UA-Compatible" content="ie=edge">code>
<title>首页</title>
<link rel="stylesheet" href="../static/css/style.css">code>
<script src="../static/js/vue.js"></script>code>
</head>
<body>
<div id='app' class="container">code>
<img src="../static/img/bg.jpg"/>code>
<div class="panel">code>
<div class="content login">code>
<div class="switch">code>
<span :class='{"active": active === "login"}' @click='go("login")'>登陆</span>code>
<span>/</span>
<span :class='{"active": active === "register"}' @click='go("register")'>注册</span>code>
</div>
<div class='form' id="fromLogin">code>
<template v-if='active === "register"'>code>
<div class="input"><input :class='{ hasValue: registerForm.email }' v-model='registerForm.email'code>
type="text" name="email" id='email'/><label for="email">邮箱</label></div>code>
<div class="input"><input :class='{ hasValue: registerForm.Username }'code>
v-model='registerForm.Username' type="text" name="Username"code>
id="username"/><label for="username">用户名</label></div>code>
<div class="input"><input :class='{ hasValue: registerForm.Password }'code>
v-model='registerForm.Password' type="password" name="Password"code>
id="Password"/><label for="Password">密码</label></div>code>
<div class="input"><input :class='{ hasValue: registerForm.repeat }' v-model='registerForm.repeat'code>
type="password" name="repeat" id="Passwordrepeat"/><labelcode>
for="Passwordrepeat">重复密码</label></div>code>
<span>忘记?</span>
<button type="submit" @click='submitRegister'>注册</button>code>
</template>
<template v-if='active === "login"'>code>
<div class="input"><input :class='{ hasValue: loginForm.Username }' v-model='loginForm.Username'code>
type="text" name="Username" id="username"/><labelcode>
for="username">用户名</label></div>code>
<div class="input"><input :class='{ hasValue: loginForm.Password }' v-model='loginForm.Password'code>
type="password" name="Password" id="Password"/><labelcode>
for="Password">密码</label></div>code>
<span>忘记?</span>
<button type="submit" @click='submitLogin'>登陆</button>code>
</template>
</div>
</div>
</div>
</div>
<script>
var vue = new Vue({
el: '#app',
data: {
active: 'login',
registerForm: { email: '', Username: '', Password: '', repeat: '' },
loginForm: { Username: '', Password: '' },
},
methods: {
go(type) {
this.active = type;
},
<!-- 在 submitLogin 方法中 -->
async submitLogin() {
try {
const response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.loginForm),
});
const data = await response.json();
console.log('服务器响应:', data);
if (data.success) {
// 登录成功,重定向到 hall.html
window.location.href = './hall';
} else {
// 登录失败,显示错误信息
this.errorMessage = '用户名或密码错误';
}
} catch (error) {
console.error('登录时发生错误:', error);
}
},
async submitRegister() {
try {
const response = await fetch('/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.registerForm),
});
const data = await response.json();
console.log('服务器响应:', data);
// 根据服务器响应处理逻辑
} catch (error) {
console.error('注册时发生错误:', error);
}
},
},
});
</script>
</body>
</html>
<2>hall.html
<!DOCTYPE html>
<html lang="en">code>
<head>
<meta charset="UTF-8">code>
<meta name="viewport" content="width=device-width, initial-scale=1.0">code>
<title>功能大厅</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
text-align: center;
}
.button {
display: inline-block;
padding: 15px 30px;
font-size: 16px;
font-weight: bold;
text-decoration: none;
color: #fff;
background-color: #3498db;
border-radius: 5px;
margin: 10px;
transition: background-color 0.3s;
}
.button:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<div class="container">code>
<h1>学生成绩管理系统</h1>
<a href="./gradeList" class="button" id="gradeManagementBtn">成绩管理</a>code>
<a href="./sa" class="button" id="subjectAnalysisBtn">学科分析</a>code>
</div>
</body>
</html>
<3>sa.html
<!DOCTYPE html>
<html lang="en">code>
<head>
<meta charset="UTF-8">code>
<meta name="viewport" content="width=device-width, initial-scale=1.0">code>
<title>学科分析</title>
<!-- 引入 layui -->
<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">code>
<script src="https://www.layuicdn.com/layui/layui.js"></script>code>
<!-- 引入 Chart.js 库 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>code>
<!-- 引入 jQuery -->
<script src="../static/plugins/jquery-3.7.1.min.js"></script>code>
<!-- 引入基本表格插件 -->
<script type="text/javascript" src="../static/js/jquery.basictable.min.js"></script>code>
<!-- 引入响应式表格插件 -->
<script type="text/javascript" src="../static/js/reponsetable.min.js"></script>code>
<!-- 引入 layer 插件 -->
<script type="text/javascript" src="../static/plugins/layer/layer.js"></script>code>
<!-- 引入 layer 默认主题样式 -->
<link rel="stylesheet" type="text/css" href="../static/plugins/layer/theme/default/layer.css">code>
<!-- 引入自定义 CSS 样式 -->
<link rel="stylesheet" type="text/css" href="../static/css/reponse.css">code>
<link rel="stylesheet" type="text/css" href="../static/css/lib/bootstrap.min.css">code>
<link rel="stylesheet" type="text/css" href="../static/css/custom.css">code>
<style type="text/css">code>
/* 新增的样式 */
body {
font-family: 'Arial', sans-serif;
margin: 20px;
}
h1 {
color: #333;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: center;
}
th {
background-color: #f2f2f2;
}
tr:hover {
background-color: #f5f5f5;
}
.layui-layer {
background: #fff;
}
</style>
</head>
<body>
<h1>学科分析</h1>
<!-- 基本表格样式 -->
<table class="layui-table">code>
<thead>
<tr>
<th></th>
<th>成绩1</th>
<th>成绩2</th>
<th>成绩3</th>
<th>成绩4</th>
<th>成绩5</th>
<th>成绩6</th>
</tr>
</thead>
<tbody>
{% for student in students %}
{% endfor %}
<tr>
<td>最高分</td>
<td>{ { max_grades.g1 }}</td>
<td>{ { max_grades.g2 }}</td>
<td>{ { max_grades.g3 }}</td>
<td>{ { max_grades.g4 }}</td>
<td>{ { max_grades.g5 }}</td>
<td>{ { max_grades.g6 }}</td>
</tr>
<tr>
<td>最低分</td>
<td>{ { min_grades.g1 }}</td>
<td>{ { min_grades.g2 }}</td>
<td>{ { min_grades.g3 }}</td>
<td>{ { min_grades.g4 }}</td>
<td>{ { min_grades.g5 }}</td>
<td>{ { min_grades.g6 }}</td>
</tr>
<tr>
<td>平均分</td>
<td>{ { avg_grades.g1 }}</td>
<td>{ { avg_grades.g2 }}</td>
<td>{ { avg_grades.g3 }}</td>
<td>{ { avg_grades.g4 }}</td>
<td>{ { avg_grades.g5 }}</td>
<td>{ { avg_grades.g6 }}</td>
</tr>
</tbody>
</table>
</body>
</html>
<4>gradeList.html
<!DOCTYPE html>
<html lang="en">code>
<head>
<meta charset="UTF-8">code>
<meta name="viewport" content="width=device-width, initial-scale=1.0">code>
<title>学生信息管理</title>
<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">code>
<script src="https://www.layuicdn.com/layui/layui.js"></script>code>
<!-- 引入 Chart.js 库 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>code>
<script src="../static/plugins/jquery-3.7.1.min.js"></script>code>
<script type="text/javascript" src="../static/js/jquery.basictable.min.js"></script>code>
<script type="text/javascript" src="../static/js/reponsetable.min.js"></script>code>
<script type="text/javascript" src="../static/plugins/layer/layer.js"></script>code>
<link rel="stylesheet" type="text/css" href="../static/plugins/layer/theme/default/layer.css">code>
<link rel="stylesheet" type="text/css" href="../static/css/reponse.css">code>
<link rel="stylesheet" type="text/css" href="../static/css/lib/bootstrap.min.css">code>
<link rel="stylesheet" type="text/css" href="../static/css/custom.css">code>
<style type="text/css">code>
.alertceng {
background: #FFFFFF;
padding: 10px;
display: none;
}
.alertceng span.title {
margin-right: 10px;
}
</style>
</head>
<body>
<div class="layui-fluid layadmin-homepage-fluid" style="background: #fff;width:90%;margin:0 auto;">code>
<div id="page">code>
<h1>学生成绩信息管理</h1>
<table id="table" class="reponsetable"></table>code>
<script type="text/html" id="editer">code>
<a class="layui-btn layui-btn-xs" onclick="scatterPlot(this)">散点图</a>code>
<a class="layui-btn layui-btn-xs" onclick="radarChart(this)">雷达图</a>code>
<a class="layui-btn layui-btn-xs" onclick="careerPlan(this)">职业规划</a>code>
<a class="layui-btn layui-btn-xs" onclick="edittr(this)">修改</a>code>
<a class="layui-btn layui-btn-xs" onclick="deleteRecord(this)">删除</a>code>
</script>
<div class="btn-container">code>
<button class="layui-btn" onclick="addNew();">新增信息</button>code>
</div>
</div>
</div>
<div id="editcontent" class="alertceng">code>
<p><span class="title">姓名:</span><input type="text" id="name"/></p>code>
<p><span class="title">成绩1:</span><input type="text" id="g1"/></p>code>
<p><span class="title">成绩2:</span><input type="text" id="g2"/></p>code>
<p><span class="title">成绩3:</span><input type="text" id="g3"/></p>code>
<p><span class="title">成绩4:</span><input type="text" id="g4"/></p>code>
<p><span class="title">成绩5:</span><input type="text" id="g5"/></p>code>
<p><span class="title">成绩6:</span><input type="text" id="g6"/></p>code>
<button id="saveBtn">保存</button>code>
<button id="cancelBtn">取消</button>code>
</div>
<script type="text/javascript">code>
$(document).ready(function () {
// 使用后端传递的数据
fetch("/get_student_data")
.then(response => response.json())
.then(data => {
// 获取从后端获取的学生信息数据
var studentData = data.data;
// 原始数据,json构建
$('#table').basictable({
breakpoint: 768
});
// 使用后端传递的数据
$("#table").reponsetable({
"id": "table",
"operation": "editer",
"type": "numbers",
"colum": [
{"field": "name", "title": "姓名"},
{"field": "g1", "title": "成绩1"},
{"field": "g2", "title": "成绩2"},
{"field": "g3", "title": "成绩3"},
{"field": "g4", "title": "成绩4"},
{"field": "g5", "title": "成绩5"},
{"field": "g6", "title": "成绩6"}
],
"data": studentData // 使用后端传递的数据
});
// 定义按钮事件
layui.use('layer', function () {
layer = layui.layer;
});
})
.catch(error => console.error('获取学生信息数据时发生错误:', error));
// 显示表单
window.addNew = function () {
$('#editcontent').show();
}
// 保存按钮点击事件
$('#saveBtn').on('click', function () {
// 保存操作
var newData = {
"name": $("#name").val(),
"g1": $("#g1").val(),
"g2": $("#g2").val(),
"g3": $("#g3").val(),
"g4": $("#g4").val(),
"g5": $("#g5").val(),
"g6": $("#g6").val()
};
// 发送异步请求保存到数据库
$.ajax({
type: 'POST',
url: '/saveDataToDatabase',
data: JSON.stringify(newData),
contentType: 'application/json',
success: function (response) {
// 处理保存成功的逻辑
if (response.success) {
// 这里可以根据实际情况做一些提示或者刷新表格等操作
console.log('数据保存成功');
// 隐藏表单
$('#editcontent').hide();
// 清空输入框
$('#editcontent input').val('');
// 刷新表格数据
refreshTable();
} else {
console.error('数据保存失败');
}
},
error: function (error) {
console.error('保存数据时发生错误:', error);
}
});
});
// 取消按钮点击事件
$('#cancelBtn').on('click', function () {
// 隐藏表单
$('#editcontent').hide();
// 清空输入框
$('#editcontent input').val('');
});
// 定义刷新表格数据的函数
function refreshTable() {
fetch("/get_student_data")
.then(response => response.json())
.then(data => {
// 获取从后端获取的学生信息数据
var studentData = data.data;
$("#table").reponsetable("setData", studentData);
})
.catch(error => console.error('获取学生信息数据时发生错误:', error));
}
// 散点图按钮点击事件
function scatterPlot(obj) {
// 散点图按钮点击事件处理逻辑
// ...
}
// 雷达图按钮点击事件
function radarChart(obj) {
// 雷达图按钮点击事件处理逻辑
// ...
}
// 职业规划按钮点击事件
function careerPlan(obj) {
// 职业规划按钮点击事件处理逻辑
// ...
}
//删除
// 删除按钮点击事件
window.deleteRecord = function (obj) {
var currentRowData = getCurrentRowData(obj);
// 发送删除请求
$.ajax({
type: 'POST',
url: '/deleteRecord',
data: JSON.stringify(currentRowData),
contentType: 'application/json',
success: function (response) {
if (response.success) {
console.log('数据删除成功');
// 刷新表格数据
refreshTable();
} else {
console.error('数据删除失败');
}
},
error: function (error) {
console.error('删除数据时发生错误:', error);
}
});
}
// 获取当前行的学生信息
function getCurrentRowData(obj) {
var currentRow = $(obj).closest('tr');
var rowData = {
name: currentRow.find('td[data-field="name"]').text(),code>
g1: currentRow.find('td[data-field="g1"]').text(),code>
g2: currentRow.find('td[data-field="g2"]').text(),code>
// 添加其他成绩项
};
return rowData;
}
// 修改按钮点击事件
window.edittr=function (obj) {
// 获取当前行的数据
// 获取当前行的数据
var currentRowData = getCurrentRowData(obj);
// 将数据填充到表单中
$('#name').val(currentRowData.name).prop('readonly', true); // 设置为只读
$('#g1').val(currentRowData.g1);
$('#g2').val(currentRowData.g2);
$('#g3').val(currentRowData.g3);
$('#g4').val(currentRowData.g4);
$('#g5').val(currentRowData.g5);
$('#g6').val(currentRowData.g6);
// 显示表单
$('#editcontent').show();
}
// 保存按钮点击事件
$('#saveBtn').on('click', function () {
// 保存操作
var newData = {
"name": $("#name").val(),
"g1": $("#g1").val(),
"g2": $("#g2").val(),
"g3": $("#g3").val(),
"g4": $("#g4").val(),
"g5": $("#g5").val(),
"g6": $("#g6").val()
};
// 发送异步请求保存到数据库
$.ajax({
type: 'POST',
url: '/updateRecord', // 修改为更新路由
data: JSON.stringify(newData),
contentType: 'application/json',
success: function (response) {
// 处理更新成功的逻辑
if (response.success) {
console.log('数据更新成功');
// 隐藏表单
$('#editcontent').hide();
// 清空输入框
$('#editcontent input').val('');
// 刷新表格数据
refreshTable();
} else {
console.error('数据更新失败');
}
},
error: function (error) {
console.error('更新数据时发生错误:', error);
}
});
});
//散点图
window.scatterPlot=function (obj) {
// 获取当前行的数据
// 获取当前行的数据
var currentRowData = getCurrentRowData(obj);
// 构建散点图数据
var scatterChartData = {
datasets: [{
label: '散点图',
data: [{
x: '成绩1',
y: currentRowData.g1
}, {
x: '成绩2',
y: currentRowData.g2
}, {
x: '成绩3',
y: currentRowData.g3
}, {
x: '成绩4',
y: currentRowData.g4
}, {
x: '成绩5',
y: currentRowData.g5
}, {
x: '成绩6',
y: currentRowData.g6
}],
backgroundColor: 'rgba(255, 99, 132, 1)' // 颜色
}]
};
// 创建 canvas 元素
var canvas = document.createElement('canvas');
canvas.width = 400; // 设置宽度
canvas.height = 400; // 设置高度
// 将 canvas 元素添加到页面
document.body.appendChild(canvas);
// 创建散点图
var ctx = canvas.getContext('2d');
new Chart(ctx, {
type: 'scatter',
data: scatterChartData,
options: {
responsive: false,
scales: {
x: {
type: 'category', // 设置 x 轴类型为分类
labels: ['成绩1', '成绩2', '成绩3', '成绩4', '成绩5', '成绩6'],
position: 'bottom'
},
y: {
type: 'linear',
position: 'left'
}
}
}
});
}
// 获取当前行的学生信息
function getCurrentRowData(obj) {
var currentRow = obj.closest('tr');
var rowData = {
name: currentRow.querySelector('td[data-field="name"]').textContent,code>
g1: parseFloat(currentRow.querySelector('td[data-field="g1"]').textContent),code>
g2: parseFloat(currentRow.querySelector('td[data-field="g2"]').textContent),code>
g3: parseFloat(currentRow.querySelector('td[data-field="g3"]').textContent),code>
g4: parseFloat(currentRow.querySelector('td[data-field="g4"]').textContent),code>
g5: parseFloat(currentRow.querySelector('td[data-field="g5"]').textContent),code>
g6: parseFloat(currentRow.querySelector('td[data-field="g6"]').textContent)code>
};
return rowData;
}
//雷达图
window.radarChart=function (obj) {
// 获取当前行的数据
var currentRowData = getCurrentRowData(obj);
// 构建雷达图数据
var radarChartData = {
labels: ['成绩1', '成绩2', '成绩3', '成绩4', '成绩5', '成绩6'],
datasets: [{
label: '雷达图',
data: [currentRowData.g1, currentRowData.g2, currentRowData.g3, currentRowData.g4, currentRowData.g5, currentRowData.g6],
backgroundColor: 'rgba(75, 192, 192, 0.2)', // 填充颜色
borderColor: 'rgba(75, 192, 192, 1)', // 边框颜色
borderWidth: 1 // 边框宽度
}]
};
// 创建 canvas 元素
var canvas = document.createElement('canvas');
canvas.width = 400; // 设置宽度
canvas.height = 400; // 设置高度
// 将 canvas 元素添加到页面
document.body.appendChild(canvas);
// 创建雷达图
var ctx = canvas.getContext('2d');
new Chart(ctx, {
type: 'radar',
data: radarChartData,
options: {
responsive: false,
scales: {
r: {
beginAtZero: true
}
}
}
});
}
// 获取当前行的学生信息
function getCurrentRowData(obj) {
var currentRow = obj.closest('tr');
var rowData = {
name: currentRow.querySelector('td[data-field="name"]').textContent,code>
g1: parseFloat(currentRow.querySelector('td[data-field="g1"]').textContent),code>
g2: parseFloat(currentRow.querySelector('td[data-field="g2"]').textContent),code>
g3: parseFloat(currentRow.querySelector('td[data-field="g3"]').textContent),code>
g4: parseFloat(currentRow.querySelector('td[data-field="g4"]').textContent),code>
g5: parseFloat(currentRow.querySelector('td[data-field="g5"]').textContent),code>
g6: parseFloat(currentRow.querySelector('td[data-field="g6"]').textContent)code>
};
return rowData;
}
//职业规划
// 职业规划按钮点击事件
window.careerPlan=function (obj) {
// 获取当前行的数据
var currentRowData = getCurrentRowData(obj);
// 向后端发送请求,获取职业规划结果
$.ajax({
type: 'POST',
url: '/careerPlan',
data: JSON.stringify({ g6: currentRowData.g6 }),
contentType: 'application/json',
success: function (response) {
if (response.success) {
// 显示职业规划结果
showCareerPlanDialog(response.message);
} else {
console.error('获取职业规划结果失败');
}
},
error: function (error) {
console.error('获取职业规划结果时发生错误:', error);
}
});
}
// 显示职业规划结果的对话框
function showCareerPlanDialog(message) {
layer.open({
title: '职业规划结果',
content: message,
btn: ['确定'],
yes: function (index, layero) {
// 点击确定按钮的回调,可以根据需要添加其他操作
layer.close(index);
}
});
}
});
</script>
</body>
</html>
2、其他前端代码略
三、后端代码
from flask import Flask, render_template, request, jsonify
import pymysql
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# MySQL数据库连接配置
DATABASE_CONFIG = {
'host': '127.0.0.1',
'user': 'root',
'password': 'Your_Password',
'database': 'pythonweb',
'cursorclass': pymysql.cursors.DictCursor,
}
# 创建MySQL连接
def create_connection():
return pymysql.connect(**DATABASE_CONFIG)
# 创建users表(如果不存在)
def create_table():
conn = create_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
)
''')
conn.commit()
conn.close()
# 创建表格(如果不存在)
create_table()
@app.route("/")
def index():
return render_template("index.html")
@app.route("/login", methods=['POST'])
def login():
data = request.json
username = data.get('Username')
password = data.get('Password')
# 在这里执行与数据库的交互逻辑,检查用户名和密码是否匹配
user = get_user(username, password)
# 在登录成功时返回一个 success 字段
if user:
return jsonify({'success': True, 'message': '登录成功'})
else:
return jsonify({'success': False, 'message': '无效的用户名或密码'}), 401
def get_user(username, password):
conn = create_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE username = %s AND password = %s', (username, password)) #参数化查询,避免sql注入
user = cursor.fetchone() #将查询结果这一行数据赋值给user变量,如果未查询到则为空
conn.close()
return user #返回查询得到的数据
# 创建grades表(如果不存在)
def create_grades_table():
conn = create_connection()
cursor = conn.cursor()
cursor.execute('''
create table if not exists grade(
name varchar(255) not null,
g1 int not null ,
g2 int not null ,
g3 int not null ,
g4 int not null ,
g5 int not null ,
g6 int not null
)
''')
conn.commit()
conn.close()
# 创建表格(如果不存在)
create_grades_table()
# 路由用于保存数据到数据库
@app.route("/saveDataToDatabase", methods=['POST'])
def save_data_to_database():
data = request.json
name = data.get('name')
g1 = data.get('g1')
g2 = data.get('g2')
g3 = data.get('g3')
g4 = data.get('g4')
g5 = data.get('g5')
g6 = data.get('g6')
# 在这里执行与数据库的交互逻辑,将数据保存到数据库
success = save_data_to_db(name, g1, g2, g3, g4, g5, g6)
# 响应
if success:
return jsonify({'success': True, 'message': '数据保存成功'})
else:
return jsonify({'success': False, 'message': '数据保存失败'}), 500
def save_data_to_db(name, g1, g2, g3, g4, g5, g6):
try:
conn = create_connection()
cursor = conn.cursor()
cursor.execute('INSERT INTO grade (name, g1, g2, g3, g4, g5, g6) VALUES (%s, %s, %s, %s, %s, %s, %s)',
(name, g1, g2, g3, g4, g5, g6))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error saving data to database: {e}")
return False
# 跳转hall.html界面的路由函数
@app.route("/hall")
def hall():
return render_template("hall.html")
# 跳转gradeList.html界面的路由函数
@app.route("/gradeList")
def gL():
return render_template("gradeList.html")
@app.route("/get_student_data")
def get_student_data():
conn = create_connection()
cursor = conn.cursor()
cursor.execute('SELECT name, g1, g2, g3, g4, g5, g6 FROM grade')
student_data = cursor.fetchall()
conn.close()
return jsonify({"data": student_data})
# 删除路由
# 路由用于删除数据
@app.route("/deleteRecord", methods=['POST'])
def delete_record():
data = request.json
name = data.get('name')
g1 = data.get('g1')
g2 = data.get('g2')
# 添加其他成绩项
# 在这里执行与数据库的交互逻辑,将数据从数据库中删除
success = delete_record_from_db(name, g1, g2)
# 响应
if success:
return jsonify({'success': True, 'message': '数据删除成功'})
else:
return jsonify({'success': False, 'message': '数据删除失败'}), 500
def delete_record_from_db(name, g1, g2):
try:
conn = create_connection()
cursor = conn.cursor()
cursor.execute('DELETE FROM grade WHERE name = %s AND g1 = %s AND g2 = %s',
(name, g1, g2))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error deleting data from database: {e}")
return False
# 路由用于更新数据
@app.route("/updateRecord", methods=['POST'])
def update_record():
data = request.json
name = data.get('name')
g1 = data.get('g1')
g2 = data.get('g2')
g3 = data.get('g3')
g4 = data.get('g4')
g5 = data.get('g5')
g6 = data.get('g6')
# 在这里执行与数据库的交互逻辑,将数据更新到数据库
success = update_record_in_db(name, g1, g2, g3, g4, g5, g6)
# 响应
if success:
return jsonify({'success': True, 'message': '数据更新成功'})
else:
return jsonify({'success': False, 'message': '数据更新失败'}), 500
def update_record_in_db(name, g1, g2, g3, g4, g5, g6):
try:
conn = create_connection()
cursor = conn.cursor()
cursor.execute('UPDATE grade SET g1=%s, g2=%s, g3=%s, g4=%s, g5=%s, g6=%s WHERE name=%s',
(g1, g2, g3, g4, g5, g6, name))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error updating data in database: {e}")
return False
# 路由用于职业规划
@app.route("/careerPlan", methods=['POST'])
def career_plan():
data = request.json
g6 = data.get('g6')
# 根据成绩6进行职业规划
career = plan_career(int(g6))
# 响应
return jsonify({'success': True, 'message': career})
# 根据成绩6进行职业规划
def plan_career(g6):
if g6 > 100:
return '黑客'
elif 80 <= g6 <= 100:
return '算法设计师'
elif 60 <= g6 < 80:
return '运维工程师'
elif 40 <= g6 < 60:
return '电脑维修工'
else:
return '板砖'
@app.route("/sa")
def sa():
conn = create_connection()
cursor = conn.cursor()
cursor.execute('SELECT name, g1, g2, g3, g4, g5, g6 FROM grade')
students = cursor.fetchall()
# 计算最高分、最低分和平均分
max_grades = {'g1': max(student['g1'] for student in students),
'g2': max(student['g2'] for student in students),
'g3': max(student['g3'] for student in students),
'g4': max(student['g4'] for student in students),
'g5': max(student['g5'] for student in students),
'g6': max(student['g6'] for student in students)}
min_grades = {'g1': min(student['g1'] for student in students),
'g2': min(student['g2'] for student in students),
'g3': min(student['g3'] for student in students),
'g4': min(student['g4'] for student in students),
'g5': min(student['g5'] for student in students),
'g6': min(student['g6'] for student in students)}
avg_grades = {'g1': sum(student['g1'] for student in students) / len(students),
'g2': sum(student['g2'] for student in students) / len(students),
'g3': sum(student['g3'] for student in students) / len(students),
'g4': sum(student['g4'] for student in students) / len(students),
'g5': sum(student['g5'] for student in students) / len(students),
'g6': sum(student['g6'] for student in students) / len(students)}
conn.close()
return render_template("sa.html", students=students, max_grades=max_grades, min_grades=min_grades,
avg_grades=avg_grades)
if __name__ == '__main__':
app.run(debug=True)
上一篇: 全网最适合入门的面向对象编程教程:27 类和对象的Python实现-Python中异常层级与自定义异常类的实现
下一篇: SpringBoot2.7 霸王硬上弓 Logback1.3 → 不甜但解渴
本文标签
声明
本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。