Flask创建学生信息管理简单界面
立即下载
资源介绍:
学生管理界面,Python环境安装Flask即可运行,可学习css和html。代码完全由AI生成。
from flask import Flask, render_template, request, redirect, url_for
import json
import os
app = Flask(__name__)
DATA_FILE = 'data/students.json'
def load_students():
if not os.path.exists(DATA_FILE):
return []
with open(DATA_FILE, 'r') as file:
try:
return json.load(file)
except json.decoder.JSONDecodeError:
return []
def save_students(students):
with open(DATA_FILE, 'w') as file:
json.dump(students, file, indent=4)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/add_student', methods=['GET', 'POST'])
def add_student():
if request.method == 'POST':
students = load_students()
new_student = {
'name': request.form['name'],
'id': request.form['id'],
'score': float(request.form['score'])
}
students.append(new_student)
save_students(students)
return redirect(url_for('view_students'))
return render_template('add_student.html')
@app.route('/view_students')
def view_students():
students = load_students()
return render_template('view_students.html', students=students)
@app.route('/edit_student/', methods=['GET', 'POST'])
def edit_student(student_id):
students = load_students()
student = next((s for s in students if s['id'] == student_id), None)
if student is None:
return "Student not found", 404
if request.method == 'POST':
student['name'] = request.form['name']
student['score'] = float(request.form['score'])
save_students(students)
return redirect(url_for('view_students'))
return render_template('edit_student.html', student=student)
@app.route('/delete_student/')
def delete_student(student_id):
students = load_students()
students = [s for s in students if s['id'] != student_id]
save_students(students)
return redirect(url_for('view_students'))
if __name__ == '__main__':
app.run(debug=True)