当前位置:   article > 正文

Python课设-学生信息管理系统

python课设

一、效果展示图

二、前端代码

1、HTML代码

<1>index.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>首页</title>
  8. <link rel="stylesheet" href="../static/css/style.css">
  9. <script src="../static/js/vue.js"></script>
  10. </head>
  11. <body>
  12. <div id='app' class="container">
  13. <img src="../static/img/bg.jpg"/>
  14. <div class="panel">
  15. <div class="content login">
  16. <div class="switch">
  17. <span :class='{"active": active === "login"}' @click='go("login")'>登陆</span>
  18. <span>/</span>
  19. <span :class='{"active": active === "register"}' @click='go("register")'>注册</span>
  20. </div>
  21. <div class='form' id="fromLogin">
  22. <template v-if='active === "register"'>
  23. <div class="input"><input :class='{ hasValue: registerForm.email }' v-model='registerForm.email'
  24. type="text" name="email" id='email'/><label for="email">邮箱</label></div>
  25. <div class="input"><input :class='{ hasValue: registerForm.Username }'
  26. v-model='registerForm.Username' type="text" name="Username"
  27. id="username"/><label for="username">用户名</label></div>
  28. <div class="input"><input :class='{ hasValue: registerForm.Password }'
  29. v-model='registerForm.Password' type="password" name="Password"
  30. id="Password"/><label for="Password">密码</label></div>
  31. <div class="input"><input :class='{ hasValue: registerForm.repeat }' v-model='registerForm.repeat'
  32. type="password" name="repeat" id="Passwordrepeat"/><label
  33. for="Passwordrepeat">重复密码</label></div>
  34. <span>忘记?</span>
  35. <button type="submit" @click='submitRegister'>注册</button>
  36. </template>
  37. <template v-if='active === "login"'>
  38. <div class="input"><input :class='{ hasValue: loginForm.Username }' v-model='loginForm.Username'
  39. type="text" name="Username" id="username"/><label
  40. for="username">用户名</label></div>
  41. <div class="input"><input :class='{ hasValue: loginForm.Password }' v-model='loginForm.Password'
  42. type="password" name="Password" id="Password"/><label
  43. for="Password">密码</label></div>
  44. <span>忘记?</span>
  45. <button type="submit" @click='submitLogin'>登陆</button>
  46. </template>
  47. </div>
  48. </div>
  49. </div>
  50. </div>
  51. <script>
  52. var vue = new Vue({
  53. el: '#app',
  54. data: {
  55. active: 'login',
  56. registerForm: { email: '', Username: '', Password: '', repeat: '' },
  57. loginForm: { Username: '', Password: '' },
  58. },
  59. methods: {
  60. go(type) {
  61. this.active = type;
  62. },
  63. <!-- 在 submitLogin 方法中 -->
  64. async submitLogin() {
  65. try {
  66. const response = await fetch('/login', {
  67. method: 'POST',
  68. headers: {
  69. 'Content-Type': 'application/json',
  70. },
  71. body: JSON.stringify(this.loginForm),
  72. });
  73. const data = await response.json();
  74. console.log('服务器响应:', data);
  75. if (data.success) {
  76. // 登录成功,重定向到 hall.html
  77. window.location.href = './hall';
  78. } else {
  79. // 登录失败,显示错误信息
  80. this.errorMessage = '用户名或密码错误';
  81. }
  82. } catch (error) {
  83. console.error('登录时发生错误:', error);
  84. }
  85. },
  86. async submitRegister() {
  87. try {
  88. const response = await fetch('/register', {
  89. method: 'POST',
  90. headers: {
  91. 'Content-Type': 'application/json',
  92. },
  93. body: JSON.stringify(this.registerForm),
  94. });
  95. const data = await response.json();
  96. console.log('服务器响应:', data);
  97. // 根据服务器响应处理逻辑
  98. } catch (error) {
  99. console.error('注册时发生错误:', error);
  100. }
  101. },
  102. },
  103. });
  104. </script>
  105. </body>
  106. </html>
<2>hall.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>功能大厅</title>
  7. <style>
  8. body {
  9. font-family: Arial, sans-serif;
  10. background-color: #f4f4f4;
  11. margin: 0;
  12. padding: 0;
  13. display: flex;
  14. justify-content: center;
  15. align-items: center;
  16. height: 100vh;
  17. }
  18. .container {
  19. text-align: center;
  20. }
  21. .button {
  22. display: inline-block;
  23. padding: 15px 30px;
  24. font-size: 16px;
  25. font-weight: bold;
  26. text-decoration: none;
  27. color: #fff;
  28. background-color: #3498db;
  29. border-radius: 5px;
  30. margin: 10px;
  31. transition: background-color 0.3s;
  32. }
  33. .button:hover {
  34. background-color: #2980b9;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <div class="container">
  40. <h1>学生成绩管理系统</h1>
  41. <a href="./gradeList" class="button" id="gradeManagementBtn">成绩管理</a>
  42. <a href="./sa" class="button" id="subjectAnalysisBtn">学科分析</a>
  43. </div>
  44. </body>
  45. </html>
<3>sa.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>学科分析</title>
  7. <!-- 引入 layui -->
  8. <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
  9. <script src="https://www.layuicdn.com/layui/layui.js"></script>
  10. <!-- 引入 Chart.js 库 -->
  11. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  12. <!-- 引入 jQuery -->
  13. <script src="../static/plugins/jquery-3.7.1.min.js"></script>
  14. <!-- 引入基本表格插件 -->
  15. <script type="text/javascript" src="../static/js/jquery.basictable.min.js"></script>
  16. <!-- 引入响应式表格插件 -->
  17. <script type="text/javascript" src="../static/js/reponsetable.min.js"></script>
  18. <!-- 引入 layer 插件 -->
  19. <script type="text/javascript" src="../static/plugins/layer/layer.js"></script>
  20. <!-- 引入 layer 默认主题样式 -->
  21. <link rel="stylesheet" type="text/css" href="../static/plugins/layer/theme/default/layer.css">
  22. <!-- 引入自定义 CSS 样式 -->
  23. <link rel="stylesheet" type="text/css" href="../static/css/reponse.css">
  24. <link rel="stylesheet" type="text/css" href="../static/css/lib/bootstrap.min.css">
  25. <link rel="stylesheet" type="text/css" href="../static/css/custom.css">
  26. <style type="text/css">
  27. /* 新增的样式 */
  28. body {
  29. font-family: 'Arial', sans-serif;
  30. margin: 20px;
  31. }
  32. h1 {
  33. color: #333;
  34. }
  35. table {
  36. width: 100%;
  37. border-collapse: collapse;
  38. margin-top: 20px;
  39. }
  40. th, td {
  41. padding: 10px;
  42. border: 1px solid #ddd;
  43. text-align: center;
  44. }
  45. th {
  46. background-color: #f2f2f2;
  47. }
  48. tr:hover {
  49. background-color: #f5f5f5;
  50. }
  51. .layui-layer {
  52. background: #fff;
  53. }
  54. </style>
  55. </head>
  56. <body>
  57. <h1>学科分析</h1>
  58. <!-- 基本表格样式 -->
  59. <table class="layui-table">
  60. <thead>
  61. <tr>
  62. <th></th>
  63. <th>成绩1</th>
  64. <th>成绩2</th>
  65. <th>成绩3</th>
  66. <th>成绩4</th>
  67. <th>成绩5</th>
  68. <th>成绩6</th>
  69. </tr>
  70. </thead>
  71. <tbody>
  72. {% for student in students %}
  73. {% endfor %}
  74. <tr>
  75. <td>最高分</td>
  76. <td>{{ max_grades.g1 }}</td>
  77. <td>{{ max_grades.g2 }}</td>
  78. <td>{{ max_grades.g3 }}</td>
  79. <td>{{ max_grades.g4 }}</td>
  80. <td>{{ max_grades.g5 }}</td>
  81. <td>{{ max_grades.g6 }}</td>
  82. </tr>
  83. <tr>
  84. <td>最低分</td>
  85. <td>{{ min_grades.g1 }}</td>
  86. <td>{{ min_grades.g2 }}</td>
  87. <td>{{ min_grades.g3 }}</td>
  88. <td>{{ min_grades.g4 }}</td>
  89. <td>{{ min_grades.g5 }}</td>
  90. <td>{{ min_grades.g6 }}</td>
  91. </tr>
  92. <tr>
  93. <td>平均分</td>
  94. <td>{{ avg_grades.g1 }}</td>
  95. <td>{{ avg_grades.g2 }}</td>
  96. <td>{{ avg_grades.g3 }}</td>
  97. <td>{{ avg_grades.g4 }}</td>
  98. <td>{{ avg_grades.g5 }}</td>
  99. <td>{{ avg_grades.g6 }}</td>
  100. </tr>
  101. </tbody>
  102. </table>
  103. </body>
  104. </html>

<4>gradeList.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>学生信息管理</title>
  7. <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
  8. <script src="https://www.layuicdn.com/layui/layui.js"></script>
  9. <!-- 引入 Chart.js 库 -->
  10. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  11. <script src="../static/plugins/jquery-3.7.1.min.js"></script>
  12. <script type="text/javascript" src="../static/js/jquery.basictable.min.js"></script>
  13. <script type="text/javascript" src="../static/js/reponsetable.min.js"></script>
  14. <script type="text/javascript" src="../static/plugins/layer/layer.js"></script>
  15. <link rel="stylesheet" type="text/css" href="../static/plugins/layer/theme/default/layer.css">
  16. <link rel="stylesheet" type="text/css" href="../static/css/reponse.css">
  17. <link rel="stylesheet" type="text/css" href="../static/css/lib/bootstrap.min.css">
  18. <link rel="stylesheet" type="text/css" href="../static/css/custom.css">
  19. <style type="text/css">
  20. .alertceng {
  21. background: #FFFFFF;
  22. padding: 10px;
  23. display: none;
  24. }
  25. .alertceng span.title {
  26. margin-right: 10px;
  27. }
  28. </style>
  29. </head>
  30. <body>
  31. <div class="layui-fluid layadmin-homepage-fluid" style="background: #fff;width:90%;margin:0 auto;">
  32. <div id="page">
  33. <h1>学生成绩信息管理</h1>
  34. <table id="table" class="reponsetable"></table>
  35. <script type="text/html" id="editer">
  36. <a class="layui-btn layui-btn-xs" onclick="scatterPlot(this)">散点图</a>
  37. <a class="layui-btn layui-btn-xs" onclick="radarChart(this)">雷达图</a>
  38. <a class="layui-btn layui-btn-xs" onclick="careerPlan(this)">职业规划</a>
  39. <a class="layui-btn layui-btn-xs" onclick="edittr(this)">修改</a>
  40. <a class="layui-btn layui-btn-xs" onclick="deleteRecord(this)">删除</a>
  41. </script>
  42. <div class="btn-container">
  43. <button class="layui-btn" onclick="addNew();">新增信息</button>
  44. </div>
  45. </div>
  46. </div>
  47. <div id="editcontent" class="alertceng">
  48. <p><span class="title">姓名:</span><input type="text" id="name"/></p>
  49. <p><span class="title">成绩1:</span><input type="text" id="g1"/></p>
  50. <p><span class="title">成绩2:</span><input type="text" id="g2"/></p>
  51. <p><span class="title">成绩3:</span><input type="text" id="g3"/></p>
  52. <p><span class="title">成绩4:</span><input type="text" id="g4"/></p>
  53. <p><span class="title">成绩5:</span><input type="text" id="g5"/></p>
  54. <p><span class="title">成绩6:</span><input type="text" id="g6"/></p>
  55. <button id="saveBtn">保存</button>
  56. <button id="cancelBtn">取消</button>
  57. </div>
  58. <script type="text/javascript">
  59. $(document).ready(function () {
  60. // 使用后端传递的数据
  61. fetch("/get_student_data")
  62. .then(response => response.json())
  63. .then(data => {
  64. // 获取从后端获取的学生信息数据
  65. var studentData = data.data;
  66. // 原始数据,json构建
  67. $('#table').basictable({
  68. breakpoint: 768
  69. });
  70. // 使用后端传递的数据
  71. $("#table").reponsetable({
  72. "id": "table",
  73. "operation": "editer",
  74. "type": "numbers",
  75. "colum": [
  76. {"field": "name", "title": "姓名"},
  77. {"field": "g1", "title": "成绩1"},
  78. {"field": "g2", "title": "成绩2"},
  79. {"field": "g3", "title": "成绩3"},
  80. {"field": "g4", "title": "成绩4"},
  81. {"field": "g5", "title": "成绩5"},
  82. {"field": "g6", "title": "成绩6"}
  83. ],
  84. "data": studentData // 使用后端传递的数据
  85. });
  86. // 定义按钮事件
  87. layui.use('layer', function () {
  88. layer = layui.layer;
  89. });
  90. })
  91. .catch(error => console.error('获取学生信息数据时发生错误:', error));
  92. // 显示表单
  93. window.addNew = function () {
  94. $('#editcontent').show();
  95. }
  96. // 保存按钮点击事件
  97. $('#saveBtn').on('click', function () {
  98. // 保存操作
  99. var newData = {
  100. "name": $("#name").val(),
  101. "g1": $("#g1").val(),
  102. "g2": $("#g2").val(),
  103. "g3": $("#g3").val(),
  104. "g4": $("#g4").val(),
  105. "g5": $("#g5").val(),
  106. "g6": $("#g6").val()
  107. };
  108. // 发送异步请求保存到数据库
  109. $.ajax({
  110. type: 'POST',
  111. url: '/saveDataToDatabase',
  112. data: JSON.stringify(newData),
  113. contentType: 'application/json',
  114. success: function (response) {
  115. // 处理保存成功的逻辑
  116. if (response.success) {
  117. // 这里可以根据实际情况做一些提示或者刷新表格等操作
  118. console.log('数据保存成功');
  119. // 隐藏表单
  120. $('#editcontent').hide();
  121. // 清空输入框
  122. $('#editcontent input').val('');
  123. // 刷新表格数据
  124. refreshTable();
  125. } else {
  126. console.error('数据保存失败');
  127. }
  128. },
  129. error: function (error) {
  130. console.error('保存数据时发生错误:', error);
  131. }
  132. });
  133. });
  134. // 取消按钮点击事件
  135. $('#cancelBtn').on('click', function () {
  136. // 隐藏表单
  137. $('#editcontent').hide();
  138. // 清空输入框
  139. $('#editcontent input').val('');
  140. });
  141. // 定义刷新表格数据的函数
  142. function refreshTable() {
  143. fetch("/get_student_data")
  144. .then(response => response.json())
  145. .then(data => {
  146. // 获取从后端获取的学生信息数据
  147. var studentData = data.data;
  148. $("#table").reponsetable("setData", studentData);
  149. })
  150. .catch(error => console.error('获取学生信息数据时发生错误:', error));
  151. }
  152. // 散点图按钮点击事件
  153. function scatterPlot(obj) {
  154. // 散点图按钮点击事件处理逻辑
  155. // ...
  156. }
  157. // 雷达图按钮点击事件
  158. function radarChart(obj) {
  159. // 雷达图按钮点击事件处理逻辑
  160. // ...
  161. }
  162. // 职业规划按钮点击事件
  163. function careerPlan(obj) {
  164. // 职业规划按钮点击事件处理逻辑
  165. // ...
  166. }
  167. //删除
  168. // 删除按钮点击事件
  169. window.deleteRecord = function (obj) {
  170. var currentRowData = getCurrentRowData(obj);
  171. // 发送删除请求
  172. $.ajax({
  173. type: 'POST',
  174. url: '/deleteRecord',
  175. data: JSON.stringify(currentRowData),
  176. contentType: 'application/json',
  177. success: function (response) {
  178. if (response.success) {
  179. console.log('数据删除成功');
  180. // 刷新表格数据
  181. refreshTable();
  182. } else {
  183. console.error('数据删除失败');
  184. }
  185. },
  186. error: function (error) {
  187. console.error('删除数据时发生错误:', error);
  188. }
  189. });
  190. }
  191. // 获取当前行的学生信息
  192. function getCurrentRowData(obj) {
  193. var currentRow = $(obj).closest('tr');
  194. var rowData = {
  195. name: currentRow.find('td[data-field="name"]').text(),
  196. g1: currentRow.find('td[data-field="g1"]').text(),
  197. g2: currentRow.find('td[data-field="g2"]').text(),
  198. // 添加其他成绩项
  199. };
  200. return rowData;
  201. }
  202. // 修改按钮点击事件
  203. window.edittr=function (obj) {
  204. // 获取当前行的数据
  205. // 获取当前行的数据
  206. var currentRowData = getCurrentRowData(obj);
  207. // 将数据填充到表单中
  208. $('#name').val(currentRowData.name).prop('readonly', true); // 设置为只读
  209. $('#g1').val(currentRowData.g1);
  210. $('#g2').val(currentRowData.g2);
  211. $('#g3').val(currentRowData.g3);
  212. $('#g4').val(currentRowData.g4);
  213. $('#g5').val(currentRowData.g5);
  214. $('#g6').val(currentRowData.g6);
  215. // 显示表单
  216. $('#editcontent').show();
  217. }
  218. // 保存按钮点击事件
  219. $('#saveBtn').on('click', function () {
  220. // 保存操作
  221. var newData = {
  222. "name": $("#name").val(),
  223. "g1": $("#g1").val(),
  224. "g2": $("#g2").val(),
  225. "g3": $("#g3").val(),
  226. "g4": $("#g4").val(),
  227. "g5": $("#g5").val(),
  228. "g6": $("#g6").val()
  229. };
  230. // 发送异步请求保存到数据库
  231. $.ajax({
  232. type: 'POST',
  233. url: '/updateRecord', // 修改为更新路由
  234. data: JSON.stringify(newData),
  235. contentType: 'application/json',
  236. success: function (response) {
  237. // 处理更新成功的逻辑
  238. if (response.success) {
  239. console.log('数据更新成功');
  240. // 隐藏表单
  241. $('#editcontent').hide();
  242. // 清空输入框
  243. $('#editcontent input').val('');
  244. // 刷新表格数据
  245. refreshTable();
  246. } else {
  247. console.error('数据更新失败');
  248. }
  249. },
  250. error: function (error) {
  251. console.error('更新数据时发生错误:', error);
  252. }
  253. });
  254. });
  255. //散点图
  256. window.scatterPlot=function (obj) {
  257. // 获取当前行的数据
  258. // 获取当前行的数据
  259. var currentRowData = getCurrentRowData(obj);
  260. // 构建散点图数据
  261. var scatterChartData = {
  262. datasets: [{
  263. label: '散点图',
  264. data: [{
  265. x: '成绩1',
  266. y: currentRowData.g1
  267. }, {
  268. x: '成绩2',
  269. y: currentRowData.g2
  270. }, {
  271. x: '成绩3',
  272. y: currentRowData.g3
  273. }, {
  274. x: '成绩4',
  275. y: currentRowData.g4
  276. }, {
  277. x: '成绩5',
  278. y: currentRowData.g5
  279. }, {
  280. x: '成绩6',
  281. y: currentRowData.g6
  282. }],
  283. backgroundColor: 'rgba(255, 99, 132, 1)' // 颜色
  284. }]
  285. };
  286. // 创建 canvas 元素
  287. var canvas = document.createElement('canvas');
  288. canvas.width = 400; // 设置宽度
  289. canvas.height = 400; // 设置高度
  290. // 将 canvas 元素添加到页面
  291. document.body.appendChild(canvas);
  292. // 创建散点图
  293. var ctx = canvas.getContext('2d');
  294. new Chart(ctx, {
  295. type: 'scatter',
  296. data: scatterChartData,
  297. options: {
  298. responsive: false,
  299. scales: {
  300. x: {
  301. type: 'category', // 设置 x 轴类型为分类
  302. labels: ['成绩1', '成绩2', '成绩3', '成绩4', '成绩5', '成绩6'],
  303. position: 'bottom'
  304. },
  305. y: {
  306. type: 'linear',
  307. position: 'left'
  308. }
  309. }
  310. }
  311. });
  312. }
  313. // 获取当前行的学生信息
  314. function getCurrentRowData(obj) {
  315. var currentRow = obj.closest('tr');
  316. var rowData = {
  317. name: currentRow.querySelector('td[data-field="name"]').textContent,
  318. g1: parseFloat(currentRow.querySelector('td[data-field="g1"]').textContent),
  319. g2: parseFloat(currentRow.querySelector('td[data-field="g2"]').textContent),
  320. g3: parseFloat(currentRow.querySelector('td[data-field="g3"]').textContent),
  321. g4: parseFloat(currentRow.querySelector('td[data-field="g4"]').textContent),
  322. g5: parseFloat(currentRow.querySelector('td[data-field="g5"]').textContent),
  323. g6: parseFloat(currentRow.querySelector('td[data-field="g6"]').textContent)
  324. };
  325. return rowData;
  326. }
  327. //雷达图
  328. window.radarChart=function (obj) {
  329. // 获取当前行的数据
  330. var currentRowData = getCurrentRowData(obj);
  331. // 构建雷达图数据
  332. var radarChartData = {
  333. labels: ['成绩1', '成绩2', '成绩3', '成绩4', '成绩5', '成绩6'],
  334. datasets: [{
  335. label: '雷达图',
  336. data: [currentRowData.g1, currentRowData.g2, currentRowData.g3, currentRowData.g4, currentRowData.g5, currentRowData.g6],
  337. backgroundColor: 'rgba(75, 192, 192, 0.2)', // 填充颜色
  338. borderColor: 'rgba(75, 192, 192, 1)', // 边框颜色
  339. borderWidth: 1 // 边框宽度
  340. }]
  341. };
  342. // 创建 canvas 元素
  343. var canvas = document.createElement('canvas');
  344. canvas.width = 400; // 设置宽度
  345. canvas.height = 400; // 设置高度
  346. // 将 canvas 元素添加到页面
  347. document.body.appendChild(canvas);
  348. // 创建雷达图
  349. var ctx = canvas.getContext('2d');
  350. new Chart(ctx, {
  351. type: 'radar',
  352. data: radarChartData,
  353. options: {
  354. responsive: false,
  355. scales: {
  356. r: {
  357. beginAtZero: true
  358. }
  359. }
  360. }
  361. });
  362. }
  363. // 获取当前行的学生信息
  364. function getCurrentRowData(obj) {
  365. var currentRow = obj.closest('tr');
  366. var rowData = {
  367. name: currentRow.querySelector('td[data-field="name"]').textContent,
  368. g1: parseFloat(currentRow.querySelector('td[data-field="g1"]').textContent),
  369. g2: parseFloat(currentRow.querySelector('td[data-field="g2"]').textContent),
  370. g3: parseFloat(currentRow.querySelector('td[data-field="g3"]').textContent),
  371. g4: parseFloat(currentRow.querySelector('td[data-field="g4"]').textContent),
  372. g5: parseFloat(currentRow.querySelector('td[data-field="g5"]').textContent),
  373. g6: parseFloat(currentRow.querySelector('td[data-field="g6"]').textContent)
  374. };
  375. return rowData;
  376. }
  377. //职业规划
  378. // 职业规划按钮点击事件
  379. window.careerPlan=function (obj) {
  380. // 获取当前行的数据
  381. var currentRowData = getCurrentRowData(obj);
  382. // 向后端发送请求,获取职业规划结果
  383. $.ajax({
  384. type: 'POST',
  385. url: '/careerPlan',
  386. data: JSON.stringify({ g6: currentRowData.g6 }),
  387. contentType: 'application/json',
  388. success: function (response) {
  389. if (response.success) {
  390. // 显示职业规划结果
  391. showCareerPlanDialog(response.message);
  392. } else {
  393. console.error('获取职业规划结果失败');
  394. }
  395. },
  396. error: function (error) {
  397. console.error('获取职业规划结果时发生错误:', error);
  398. }
  399. });
  400. }
  401. // 显示职业规划结果的对话框
  402. function showCareerPlanDialog(message) {
  403. layer.open({
  404. title: '职业规划结果',
  405. content: message,
  406. btn: ['确定'],
  407. yes: function (index, layero) {
  408. // 点击确定按钮的回调,可以根据需要添加其他操作
  409. layer.close(index);
  410. }
  411. });
  412. }
  413. });
  414. </script>
  415. </body>
  416. </html>

 2、其他前端代码略

三、后端代码

  1. from flask import Flask, render_template, request, jsonify
  2. import pymysql
  3. from flask_cors import CORS
  4. app = Flask(__name__)
  5. CORS(app)
  6. # MySQL数据库连接配置
  7. DATABASE_CONFIG = {
  8. 'host': '127.0.0.1',
  9. 'user': 'root',
  10. 'password': 'Your_Password',
  11. 'database': 'pythonweb',
  12. 'cursorclass': pymysql.cursors.DictCursor,
  13. }
  14. # 创建MySQL连接
  15. def create_connection():
  16. return pymysql.connect(**DATABASE_CONFIG)
  17. # 创建users表(如果不存在)
  18. def create_table():
  19. conn = create_connection()
  20. cursor = conn.cursor()
  21. cursor.execute('''
  22. CREATE TABLE IF NOT EXISTS users (
  23. id INT AUTO_INCREMENT PRIMARY KEY,
  24. username VARCHAR(255) NOT NULL,
  25. password VARCHAR(255) NOT NULL
  26. )
  27. ''')
  28. conn.commit()
  29. conn.close()
  30. # 创建表格(如果不存在)
  31. create_table()
  32. @app.route("/")
  33. def index():
  34. return render_template("index.html")
  35. @app.route("/login", methods=['POST'])
  36. def login():
  37. data = request.json
  38. username = data.get('Username')
  39. password = data.get('Password')
  40. # 在这里执行与数据库的交互逻辑,检查用户名和密码是否匹配
  41. user = get_user(username, password)
  42. # 在登录成功时返回一个 success 字段
  43. if user:
  44. return jsonify({'success': True, 'message': '登录成功'})
  45. else:
  46. return jsonify({'success': False, 'message': '无效的用户名或密码'}), 401
  47. def get_user(username, password):
  48. conn = create_connection()
  49. cursor = conn.cursor()
  50. cursor.execute('SELECT * FROM users WHERE username = %s AND password = %s', (username, password)) #参数化查询,避免sql注入
  51. user = cursor.fetchone() #将查询结果这一行数据赋值给user变量,如果未查询到则为空
  52. conn.close()
  53. return user #返回查询得到的数据
  54. # 创建grades表(如果不存在)
  55. def create_grades_table():
  56. conn = create_connection()
  57. cursor = conn.cursor()
  58. cursor.execute('''
  59. create table if not exists grade(
  60. name varchar(255) not null,
  61. g1 int not null ,
  62. g2 int not null ,
  63. g3 int not null ,
  64. g4 int not null ,
  65. g5 int not null ,
  66. g6 int not null
  67. )
  68. ''')
  69. conn.commit()
  70. conn.close()
  71. # 创建表格(如果不存在)
  72. create_grades_table()
  73. # 路由用于保存数据到数据库
  74. @app.route("/saveDataToDatabase", methods=['POST'])
  75. def save_data_to_database():
  76. data = request.json
  77. name = data.get('name')
  78. g1 = data.get('g1')
  79. g2 = data.get('g2')
  80. g3 = data.get('g3')
  81. g4 = data.get('g4')
  82. g5 = data.get('g5')
  83. g6 = data.get('g6')
  84. # 在这里执行与数据库的交互逻辑,将数据保存到数据库
  85. success = save_data_to_db(name, g1, g2, g3, g4, g5, g6)
  86. # 响应
  87. if success:
  88. return jsonify({'success': True, 'message': '数据保存成功'})
  89. else:
  90. return jsonify({'success': False, 'message': '数据保存失败'}), 500
  91. def save_data_to_db(name, g1, g2, g3, g4, g5, g6):
  92. try:
  93. conn = create_connection()
  94. cursor = conn.cursor()
  95. cursor.execute('INSERT INTO grade (name, g1, g2, g3, g4, g5, g6) VALUES (%s, %s, %s, %s, %s, %s, %s)',
  96. (name, g1, g2, g3, g4, g5, g6))
  97. conn.commit()
  98. conn.close()
  99. return True
  100. except Exception as e:
  101. print(f"Error saving data to database: {e}")
  102. return False
  103. # 跳转hall.html界面的路由函数
  104. @app.route("/hall")
  105. def hall():
  106. return render_template("hall.html")
  107. # 跳转gradeList.html界面的路由函数
  108. @app.route("/gradeList")
  109. def gL():
  110. return render_template("gradeList.html")
  111. @app.route("/get_student_data")
  112. def get_student_data():
  113. conn = create_connection()
  114. cursor = conn.cursor()
  115. cursor.execute('SELECT name, g1, g2, g3, g4, g5, g6 FROM grade')
  116. student_data = cursor.fetchall()
  117. conn.close()
  118. return jsonify({"data": student_data})
  119. # 删除路由
  120. # 路由用于删除数据
  121. @app.route("/deleteRecord", methods=['POST'])
  122. def delete_record():
  123. data = request.json
  124. name = data.get('name')
  125. g1 = data.get('g1')
  126. g2 = data.get('g2')
  127. # 添加其他成绩项
  128. # 在这里执行与数据库的交互逻辑,将数据从数据库中删除
  129. success = delete_record_from_db(name, g1, g2)
  130. # 响应
  131. if success:
  132. return jsonify({'success': True, 'message': '数据删除成功'})
  133. else:
  134. return jsonify({'success': False, 'message': '数据删除失败'}), 500
  135. def delete_record_from_db(name, g1, g2):
  136. try:
  137. conn = create_connection()
  138. cursor = conn.cursor()
  139. cursor.execute('DELETE FROM grade WHERE name = %s AND g1 = %s AND g2 = %s',
  140. (name, g1, g2))
  141. conn.commit()
  142. conn.close()
  143. return True
  144. except Exception as e:
  145. print(f"Error deleting data from database: {e}")
  146. return False
  147. # 路由用于更新数据
  148. @app.route("/updateRecord", methods=['POST'])
  149. def update_record():
  150. data = request.json
  151. name = data.get('name')
  152. g1 = data.get('g1')
  153. g2 = data.get('g2')
  154. g3 = data.get('g3')
  155. g4 = data.get('g4')
  156. g5 = data.get('g5')
  157. g6 = data.get('g6')
  158. # 在这里执行与数据库的交互逻辑,将数据更新到数据库
  159. success = update_record_in_db(name, g1, g2, g3, g4, g5, g6)
  160. # 响应
  161. if success:
  162. return jsonify({'success': True, 'message': '数据更新成功'})
  163. else:
  164. return jsonify({'success': False, 'message': '数据更新失败'}), 500
  165. def update_record_in_db(name, g1, g2, g3, g4, g5, g6):
  166. try:
  167. conn = create_connection()
  168. cursor = conn.cursor()
  169. cursor.execute('UPDATE grade SET g1=%s, g2=%s, g3=%s, g4=%s, g5=%s, g6=%s WHERE name=%s',
  170. (g1, g2, g3, g4, g5, g6, name))
  171. conn.commit()
  172. conn.close()
  173. return True
  174. except Exception as e:
  175. print(f"Error updating data in database: {e}")
  176. return False
  177. # 路由用于职业规划
  178. @app.route("/careerPlan", methods=['POST'])
  179. def career_plan():
  180. data = request.json
  181. g6 = data.get('g6')
  182. # 根据成绩6进行职业规划
  183. career = plan_career(int(g6))
  184. # 响应
  185. return jsonify({'success': True, 'message': career})
  186. # 根据成绩6进行职业规划
  187. def plan_career(g6):
  188. if g6 > 100:
  189. return '黑客'
  190. elif 80 <= g6 <= 100:
  191. return '算法设计师'
  192. elif 60 <= g6 < 80:
  193. return '运维工程师'
  194. elif 40 <= g6 < 60:
  195. return '电脑维修工'
  196. else:
  197. return '板砖'
  198. @app.route("/sa")
  199. def sa():
  200. conn = create_connection()
  201. cursor = conn.cursor()
  202. cursor.execute('SELECT name, g1, g2, g3, g4, g5, g6 FROM grade')
  203. students = cursor.fetchall()
  204. # 计算最高分、最低分和平均分
  205. max_grades = {'g1': max(student['g1'] for student in students),
  206. 'g2': max(student['g2'] for student in students),
  207. 'g3': max(student['g3'] for student in students),
  208. 'g4': max(student['g4'] for student in students),
  209. 'g5': max(student['g5'] for student in students),
  210. 'g6': max(student['g6'] for student in students)}
  211. min_grades = {'g1': min(student['g1'] for student in students),
  212. 'g2': min(student['g2'] for student in students),
  213. 'g3': min(student['g3'] for student in students),
  214. 'g4': min(student['g4'] for student in students),
  215. 'g5': min(student['g5'] for student in students),
  216. 'g6': min(student['g6'] for student in students)}
  217. avg_grades = {'g1': sum(student['g1'] for student in students) / len(students),
  218. 'g2': sum(student['g2'] for student in students) / len(students),
  219. 'g3': sum(student['g3'] for student in students) / len(students),
  220. 'g4': sum(student['g4'] for student in students) / len(students),
  221. 'g5': sum(student['g5'] for student in students) / len(students),
  222. 'g6': sum(student['g6'] for student in students) / len(students)}
  223. conn.close()
  224. return render_template("sa.html", students=students, max_grades=max_grades, min_grades=min_grades,
  225. avg_grades=avg_grades)
  226. if __name__ == '__main__':
  227. app.run(debug=True)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/679479
推荐阅读
相关标签
  

闽ICP备14008679号