Python Flask Web + PyQt 前后端分离的项目—学习成绩可视化分析系统

简介

使用工具:

Python,PyQt ,Flask ,MySQL

注:制作重点在网页端,因此网页端的功能更全

WEB界面展示:

系统登录分为管理员,老师,学生3部分

管理员统一管理所有的账号信息以及登录信息

老师管理,添加,修改班级,学生的成绩信息

学生只能查看成绩信息,不能做出修改

PYQT界面展示:

数据库创建:

项目目录

Project-

  • PYQT # 存放软件端的代码文件(运行login.py启动程序)
  • static # 存放静态资源(图片等)

  • templates # 存放网页端的代码

  • app.py # 启动网页端系统

  • student.sql # 数据库文件

代码

简单放一个登录的代码

python 复制代码
from flask import Flask, jsonify, render_template, request, redirect, url_for, session
import mysql.connector
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
matplotlib.use('agg')
from matplotlib.font_manager import FontProperties
from io import BytesIO
import base64
from flask import render_template_string
import os
from datetime import datetime
from collections import defaultdict



# 预设字体格式,并传给rc方法
font = {'family': 'SimHei', "size": 12}
matplotlib.rc('font', **font)  # 一次定义终身使用
# Set font properties for Chinese characters
font_prop = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=12)



app = Flask(__name__)
app.secret_key = 'your_secret_key'  # Change this to a secure secret key

# Replace these placeholders with your database connection details
DB_HOST = 'localhost'
DB_USER = 'root'
DB_PASSWORD = '123456'
DB_DATABASE = 'Student'

def connect_to_database():
    try:
        connection = mysql.connector.connect(
            host=DB_HOST,
            user=DB_USER,
            password=DB_PASSWORD,
            database=DB_DATABASE
        )
        return connection
    except mysql.connector.Error as err:
        print(f"Error: {err}")
        return None

def save_login_record(connection, role, account):
    try:
        cursor = connection.cursor()
        login_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        query = f"INSERT INTO login_record (role, account, login_time) VALUES ('{role}', '{account}', '{login_time}')"
        cursor.execute(query)
        connection.commit()
    except mysql.connector.Error as err:
        print(f"Error: {err}")
    finally:
        cursor.close()


def check_admin_login(connection, table_name, account, password, role):

    try:

        if role == '管理员':
            table_name = 'admin'
            cursor = connection.cursor()
            print(table_name,account,password,role)
            query = f"SELECT * FROM {table_name} WHERE Mainid='{account}' AND password='{password}'"

            # Implement your database query logic here
            cursor.execute(query)
            result = cursor.fetchone()

        elif role == '老师':
            table_name = 'admin_teachers'
            # Check administrator login
            cursor = connection.cursor()
            print(table_name,account,password,role)
            query = f"SELECT * FROM {table_name} WHERE Teacherid='{account}' AND password='{password}'"

            # Implement your database query logic here
            cursor.execute(query)
            result = cursor.fetchone()


        elif role == '学生':
            table_name = 'admin_students'
            # Check administrator login
            cursor = connection.cursor()
            print(table_name,account,password,role)
            query = f"SELECT * FROM {table_name} WHERE Studentid='{account}' AND password='{password}'"

            # Implement your database query logic here
            cursor.execute(query)
            result = cursor.fetchone()

        if result:
            # Save login record in data_8
            save_login_record(connection, role, account)

        return bool(result)
    except mysql.connector.Error as err:
        print(f"Error: {err}")
        return False
    finally:
        cursor.close()

@app.route('/')
def index():
    return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():
    account = request.form['account']
    password = request.form['password']
    role = request.form['role']

    connection = connect_to_database()
    if connection is None:
        return render_template('login_failed.html', message='Failed to connect to the database.')

    table_name = get_table_name(role)

    if check_admin_login(connection, table_name, account, password, role):
        session['role'] = role
        if role == '学生':
            session['account'] = account
            print("===================",session['account'])
        return redirect(url_for('admin_dashboard'))
    else:
        return render_template('login_failed.html', message='Invalid username or password.')

@app.route('/admin/dashboard')
def admin_dashboard():
    role = session.get('role')

    if role == '管理员':
        data = fetch_admin_data()
        data_1 = fetch_admin_teacher_data()
        data_2 = fetch_admin_student_data()
        data_8 = fetch_login_records()
        data_10 = populate_tree_model_10()
        return render_template('admin_dashboard.html', role=role, data=data, data_1=data_1, data_2=data_2, data_8 = data_8, data_10 = data_10)
    
    elif role == '老师':
        
        data_2 = fetch_admin_student_data()
        data_3 = populate_tree_model_2()
        data_4 = populate_tree_model_6()
        data_5 = populate_tree_model_4()
        data_6 = populate_tree_model_7()
        data_7 = populate_tree_model_5()
        data_9 = populate_tree_model_9()
        scatter_plot_files = show_images()
        data_10 = populate_tree_model_10()
        return render_template('teacher_dashboard.html',scatter_plot_files = scatter_plot_files, role=role, data_2=data_2, data_3=data_3, data_4=data_4, data_5=data_5, data_6=data_6, data_7=data_7, data_9=data_9, data_10 = data_10)
    
    elif role == '学生':
        account = session.get('account')
        data_3 = populate_tree_model_2()
        data_4 = populate_tree_model_6()
        data_5 = populate_tree_model_4()
        data_6 = populate_tree_model_7()
        data_7 = populate_tree_model_5()
        data_8 = show_info()
        print("===================----------------",session['account'])
        return render_template('student_dashboard.html', studentID=account, data_3=data_3, data_4=data_4, data_5=data_5, data_6=data_6, data_7=data_7, data_8=data_8)
    else:
        return redirect(url_for('index'))

# Add routes for other pages as needed

def get_table_name(role):
    # Implement logic to determine the table name based on the role
    if role == '管理员':
        return 'admin'
    elif role == '老师':
        return 'admin_teachers'
    elif role == '学生':
        return 'admin_students'
    else:
        return None

def fetch_login_records():
    data_8 = []
    try:
        connection = connect_to_database()
        if connection is None:
            return []

        cursor = connection.cursor()
        query = "SELECT * FROM login_record"
        cursor.execute(query)

        login_records = cursor.fetchall()

        # Convert rows to a list of dictionaries
        for row in login_records:
            data_8.append({
                'role': row[0],
                'account': row[1],
                'login_time': row[2]
            })

        return data_8
    except mysql.connector.Error as err:
        print(f"Error: {err}")
        return []
    finally:
        cursor.close()
        if connection:
            connection.close()

def fetch_admin_data():
    data = []
    try:
        # Connect to the MySQL database
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='123456',
            database='Student'
        )

        cursor = connection.cursor()

        # Execute a query to fetch data from the admin table
        query = "SELECT Mainid, Username, Password, Name FROM admin"
        cursor.execute(query)

        # Fetch all rows from the result
        rows = cursor.fetchall()

        # Convert rows to a list of dictionaries
        for row in rows:
            data.append({
                'Mainid': row[0],
                'Username': row[1],
                'Password': row[2],
                'Name': row[3]
            })

    except mysql.connector.Error as err:
        print(f"Error: {err}")

    finally:
        # Close the cursor and connection
        cursor.close()
        connection.close()

    return data

百度云链接:

链接:https://pan.baidu.com/s/13HtbUm0Wwd0RT_cY61M57A?pwd=o102

提取码:o102

--来自百度网盘超级会员V5的分享

系统可能还存在某些不完善的地方,欢迎讨论

相关推荐
Ai 编码助手11 分钟前
MySQL中distinct与group by之间的性能进行比较
数据库·mysql
白云如幻30 分钟前
MySQL排序查询
数据库·mysql
萧鼎31 分钟前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
学地理的小胖砸32 分钟前
【一些关于Python的信息和帮助】
开发语言·python
疯一样的码农32 分钟前
Python 继承、多态、封装、抽象
开发语言·python
苹果醋337 分钟前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
Python大数据分析@1 小时前
python操作CSV和excel,如何来做?
开发语言·python·excel
黑叶白树1 小时前
简单的签到程序 python笔记
笔记·python
Shy9604181 小时前
Bert完形填空
python·深度学习·bert
枝上棉蛮1 小时前
GISBox VS ArcGIS:分别适用于大型和小型项目的两款GIS软件
arcgis·gis·数据可视化·数据处理·地理信息系统·gis工具箱·gisbox