diff --git a/app/views.py b/app/views.py index ce2d23a..74702b4 100644 --- a/app/views.py +++ b/app/views.py @@ -1,4 +1,9 @@ -from flask import Flask, redirect, url_for, render_template, session, jsonify,request,send_file +import os + +import openpyxl as openpyxl +from flask import Flask, redirect, url_for, render_template, session, jsonify, request, send_file + +from utils.allowed_files import allowed_excel from db.connection import MySQLPool from config import SECRET_KEY from db.database_manager import DatabaseManager @@ -8,6 +13,7 @@ from models.User import User import logging from config import LOGGING_CONFIG from config import FILE_PATH + app = Flask(__name__, static_folder='static') app.secret_key = SECRET_KEY # 从配置文件设置 logging.basicConfig(**LOGGING_CONFIG) @@ -17,6 +23,7 @@ mysql_pool = MySQLPool() # 配置文件路径,例如指向一个 'files' 目录 app.config['FILE_PATH'] = FILE_PATH + @app.route('/') def index(): # 如果用户已登录,则重定向到主页;否则,重定向到登录页面 @@ -250,12 +257,39 @@ def get_current_teacher_courses(): # 将查询结果转换为JSON格式并返回 return jsonify(response) -@app.route('/files/') + +@app.route('/files/template.xlsx') def download_template(): - print(FILE_PATH) # 确保这个路径是你的文件实际所在的服务器路径 - path = "./files/template.xlsx" + path = os.path.join(app.config['FILE_PATH'], "template.xlsx") return send_file(path, as_attachment=True) + +@app.route('/api/receive-excel', methods=['POST']) +def receive_excel(): + # 检查是否有文件在请求中 + if 'file' not in request.files: + return jsonify({"error": "No file part"}), 400 + + file = request.files['file'] + + # 如果用户没有选择文件,浏览器也会提交一个空的文件名 + if file.filename == '': + return jsonify({"error": "No selected file"}), 400 + + # 检查文件是不是 Excel 文件 + if file and allowed_excel(file.filename): + try: + # 使用 openpyxl 读取文件内容 + workbook = openpyxl.load_workbook(file) + # TODO: 在这里处理你的Excel文件,例如读取数据 + print(workbook) + return jsonify({"message": "File successfully processed"}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 + else: + return jsonify({"error": "Invalid file type"}), 400 + + if __name__ == '__main__': app.run(debug=True)