from flask import Flask, request, send_from_directory, abort, jsonify import csv import os app = Flask(__name__) # 成绩文件的路径 csv_file_path = "scores.csv" # # 上传文件的路径 UPLOAD_FOLDER = "./uploads" os.makedirs(UPLOAD_FOLDER, exist_ok=True) # @app.route("/upload", methods=["POST"]) # def upload_file(): # 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 # # 保存文件到指定目录 # file.save(os.path.join(UPLOAD_FOLDER, file.filename)) # return "File uploaded successfully" @app.route("/download/", methods=["GET"]) def download_file(filename): try: return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True) except FileNotFoundError: abort(404) @app.route("/exp/", methods=["GET"]) def exp(filename): try: return send_from_directory("exp", filename, as_attachment=True) except FileNotFoundError: abort(404) def write_to_csv(data): """ 将成绩记录写入 CSV 文件。 """ file_exists = os.path.isfile(csv_file_path) with open(csv_file_path, mode="a", newline="", encoding="utf-8") as csvfile: fieldnames = ["time", "id", "name", "score", "running_time", "details"] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) if not file_exists: writer.writeheader() writer.writerow(data) @app.route("/upload_score", methods=["POST"]) def upload_score(): try: data = request.json if ( "name" in data and "id" in data and "score" in data and "details" in data and "running_time" in data and "time" in data ): if data["name"] == "test_name": return jsonify({"message": "请完善姓名,默认名字不记录成绩!"}), 400 elif data["id"] == "202210423xxx": return jsonify({"message": "请完善学号,默认学号不记录成绩!"}), 400 data["details"] = data["details"].replace("\n", "
") write_to_csv(data) return jsonify({"message": "成绩记录上传成功!"}), 200 else: return jsonify({"message": "数据格式错误"}), 400 except Exception as e: return jsonify({"error": str(e)}), 500 @app.route("/get_scores", methods=["GET"]) def get_scores(): try: with open(csv_file_path, mode="r", encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) scores = jsonify(list(reader)) scores.headers.add("Access-Control-Allow-Origin", "*") return scores except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == "__main__": app.run(host="0.0.0.0", port=880, debug=True)