feat: add upload scores function
This commit is contained in:
@@ -1,30 +1,77 @@
|
||||
from flask import Flask, request, send_from_directory, abort
|
||||
from flask import Flask, request, send_from_directory, abort, jsonify
|
||||
import csv
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
UPLOAD_FOLDER = './uploads'
|
||||
# 成绩文件的路径
|
||||
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 'No file part'
|
||||
|
||||
file = request.files['file']
|
||||
if file.filename == '':
|
||||
return 'No selected file'
|
||||
@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'
|
||||
return "File uploaded successfully"
|
||||
|
||||
@app.route('/download/<filename>', methods=['GET'])
|
||||
|
||||
@app.route("/download/<filename>", methods=["GET"])
|
||||
def download_file(filename):
|
||||
try:
|
||||
return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)
|
||||
except FileNotFoundError:
|
||||
abort(404)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=880)
|
||||
|
||||
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 = ["id", "name", "score", "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:
|
||||
write_to_csv(data)
|
||||
return jsonify({"message": "成绩记录上传成功!"}), 200
|
||||
else:
|
||||
return jsonify({"error": "数据格式错误"}), 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 = list(reader)
|
||||
return jsonify(scores)
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=880)
|
||||
|
||||
Reference in New Issue
Block a user