feat: support multipe project

This commit is contained in:
2024-10-06 22:24:34 +08:00
parent 77d03279fc
commit 3adf505be9
4 changed files with 47 additions and 26 deletions
+1 -1
View File
@@ -161,4 +161,4 @@ cython_debug/
#.idea/ #.idea/
uploads uploads
scores.csv *.csv
+35 -16
View File
@@ -5,14 +5,10 @@ import os
app = Flask(__name__) app = Flask(__name__)
# 成绩文件的路径 # 上传文件的路径
csv_file_path = "scores.csv"
# # 上传文件的路径
UPLOAD_FOLDER = "./uploads" UPLOAD_FOLDER = "./uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True) os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# @app.route("/upload", methods=["POST"]) # @app.route("/upload", methods=["POST"])
# def upload_file(): # def upload_file():
# if "file" not in request.files: # if "file" not in request.files:
@@ -43,13 +39,27 @@ def exp(filename):
abort(404) abort(404)
def write_to_csv(data): def get_csv_file_path(project):
"""根据项目名称返回CSV文件路径"""
return f"{project}_scores.csv"
def write_to_csv(data, project):
""" """
将成绩记录写入 CSV 文件。 将成绩记录写入 CSV 文件。根据项目名称选择CSV文件路径。
""" """
csv_file_path = get_csv_file_path(project)
file_exists = os.path.isfile(csv_file_path) file_exists = os.path.isfile(csv_file_path)
with open(csv_file_path, mode="a", newline="", encoding="utf-8") as csvfile: with open(csv_file_path, mode="a", newline="", encoding="utf-8") as csvfile:
fieldnames = ["time", "id", "name", "score", "running_time", "details"] fieldnames = [
"time",
"id",
"name",
"score",
"running_time",
"details",
"project",
]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not file_exists: if not file_exists:
@@ -69,23 +79,28 @@ def upload_score():
and "details" in data and "details" in data
and "running_time" in data and "running_time" in data
and "time" in data and "time" in data
and "project" in data # 新增项目名称字段
): ):
if data["name"] == "test_name": if data["name"] == "test_name":
return jsonify({"message": "请完善姓名,默认名字不记录成绩!"}), 400 return jsonify({"message": "请完善姓名,默认名字不记录成绩!"}), 400
elif data["id"] == "202210423xxx": elif data["id"] == "202210423xxx":
return jsonify({"message": "请完善学号,默认学号不记录成绩!"}), 400 return jsonify({"message": "请完善学号,默认学号不记录成绩!"}), 400
data["details"] = data["details"].replace("\n", "<br>") data["details"] = data["details"].replace("\n", "<br>")
write_to_csv(data) write_to_csv(data, data["project"])
return jsonify({"message": "成绩记录上传成功!"}), 200 return jsonify({"message": "上传成绩成功!"}), 200
else: else:
return jsonify({"message": "数据格式错误"}), 400 return jsonify({"message": "数据格式错误!"}), 400
except Exception as e: except Exception as e:
return jsonify({"error": str(e)}), 500 return jsonify({"message": f"错误 {str(e)}"}), 500
@app.route("/get_scores", methods=["GET"]) @app.route("/get_scores/<project>", methods=["GET"])
def get_scores(): def get_scores(project):
try: try:
csv_file_path = get_csv_file_path(project) # 根据项目名称选择文件
if not os.path.exists(csv_file_path):
return jsonify([]) # 如果文件不存在,返回空列表
with open(csv_file_path, mode="r", encoding="utf-8") as csvfile: with open(csv_file_path, mode="r", encoding="utf-8") as csvfile:
reader = csv.DictReader(csvfile) reader = csv.DictReader(csvfile)
data = list(reader) data = list(reader)
@@ -105,9 +120,13 @@ def get_scores():
return jsonify({"error": str(e)}), 500 return jsonify({"error": str(e)}), 500
@app.route("/get_top_scores", methods=["GET"]) @app.route("/get_top_scores/<project>", methods=["GET"])
def get_top_scores(): def get_top_scores(project):
try: try:
csv_file_path = get_csv_file_path(project) # 根据项目名称选择文件
if not os.path.exists(csv_file_path):
return jsonify([]) # 如果文件不存在,返回空列表
with open(csv_file_path, mode="r", encoding="utf-8") as csvfile: with open(csv_file_path, mode="r", encoding="utf-8") as csvfile:
reader = csv.DictReader(csvfile) reader = csv.DictReader(csvfile)
scores = list(reader) scores = list(reader)
+7 -7
View File
@@ -1,8 +1,8 @@
const BACKEND_URL = "https://rank.intcplab.cn"; const BACKEND_URL = "https://rank.intcplab.cn";
async function fetchScoresData(para, inject) { async function fetchScoresData(para, project, inject) {
try { try {
const response = await fetch(`${BACKEND_URL}/${para}`); const response = await fetch(`${BACKEND_URL}/${para}/${project}`);
const data = await response.json(); const data = await response.json();
const tableBody = document.getElementById(`${inject}`); const tableBody = document.getElementById(`${inject}`);
@@ -18,7 +18,7 @@ async function fetchScoresData(para, inject) {
<td>${item.score}</td> <td>${item.score}</td>
<td>${item.running_time}</td> <td>${item.running_time}</td>
<td> <td>
<button onclick="showDetailsModal('${para}', ${index})">查看详情</button> <button onclick="showDetailsModal('${para}', '${project}', ${index})">查看详情</button>
</td> </td>
`; `;
@@ -41,11 +41,11 @@ async function fetchScoresData(para, inject) {
} }
} }
function showDetailsModal(para, index) { function showDetailsModal(para, project, index) {
const modal = document.getElementById("detailsModal"); const modal = document.getElementById("detailsModal");
const modalDetails = document.getElementById("modal-details"); const modalDetails = document.getElementById("modal-details");
console.log(para, index); console.log(para, index);
fetch(`${BACKEND_URL}/${para}`) fetch(`${BACKEND_URL}/${para}/${project}`)
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
modalDetails.innerHTML = data[index].details + "<br><br>"; modalDetails.innerHTML = data[index].details + "<br><br>";
@@ -53,5 +53,5 @@ function showDetailsModal(para, index) {
}); });
} }
window.onload = fetchScoresData("get_top_scores", "top-data-table-body"); window.onload = fetchScoresData("get_top_scores", "challenge_knn", "top-data-table-body");
window.onload = fetchScoresData("get_scores", "recent-data-table-body"); window.onload = fetchScoresData("get_scores", "challenge_knn", "recent-data-table-body");
+4 -2
View File
@@ -5,6 +5,7 @@ import time
import traceback import traceback
EXP_URL = "http://10.2.1.195:880" EXP_URL = "http://10.2.1.195:880"
PROJECT_NAME = "challenge_knn"
def load_user_function(file_path, function_name): def load_user_function(file_path, function_name):
@@ -93,11 +94,12 @@ def upload_score(name, id, score_data):
"%Y-%m-%d %H:%M:%S", time.gmtime(time.time() + 8 * 3600) "%Y-%m-%d %H:%M:%S", time.gmtime(time.time() + 8 * 3600)
), ),
"details": score_data["details"], "details": score_data["details"],
"project": PROJECT_NAME,
}, },
) )
if response.status_code == 200: if response.status_code == 200:
print("上传成绩成功!") print(f"{response.json()["message"]}")
elif response.status_code == 400: else:
print("上传成绩失败!\n原因:", response.json()["message"]) print("上传成绩失败!\n原因:", response.json()["message"])
except Exception as e: except Exception as e:
print(f"上传成绩出错: {e}") print(f"上传成绩出错: {e}")