feat: more sort rules

This commit is contained in:
2024-10-11 19:52:10 +08:00
parent fe49b71085
commit 3fbf010724
3 changed files with 98 additions and 216 deletions
+3 -163
View File
@@ -1,164 +1,4 @@
# ---> Python __pycache__
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
uploads uploads
*.csv *.csv
temp*
+25 -53
View File
@@ -1,4 +1,5 @@
from flask import Flask, request, send_from_directory, abort, jsonify from flask import Flask, request, send_from_directory, abort, jsonify
from sort_rule import sort_by_rule
import csv import csv
import datetime import datetime
import os import os
@@ -99,68 +100,39 @@ def upload_score():
@app.route("/get_scores/<project>", methods=["GET"]) @app.route("/get_scores/<project>", methods=["GET"])
def get_scores(project): def get_scores(project):
try: try:
# CSV 文件路径 # 获取排序字段
sort_by = request.args.get("sort_by", "time")
limit = request.args.get("limit")
# 获取 CSV 文件
csv_file_path = get_csv_file_path(project) csv_file_path = get_csv_file_path(project)
if not os.path.exists(csv_file_path): if not os.path.exists(csv_file_path):
return jsonify([]) 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 = [
data.sort( {
key=lambda x: datetime.datetime.strptime( **row,
x["time"], "%Y-%m-%d %H:%M:%S" "time": datetime.datetime.strptime(
), row["time"], "%Y-%m-%d %H:%M:%S"
reverse=True, ),
) "score": float(row["score"]),
scores = jsonify(data[:30]) "running_time": float(row["running_time"].replace("ms", "")),
}
for row in reader
]
scores.headers.add("Access-Control-Allow-Origin", "*") # 根据 sort_by 排序
scores.headers.add("Cache-Control", "public, max-age=300") scores = sort_by_rule(data, sort_by, limit)
return scores
except Exception as e:
return jsonify({"error": str(e)}), 500
# 设置缓存和跨域头
response = jsonify(scores)
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Cache-Control", "public, max-age=300")
return response
@app.route("/get_top_scores/<project>", methods=["GET"])
def get_top_scores(project):
try:
# CSV 文件路径
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:
reader = csv.DictReader(csvfile)
scores = list(reader)
# 数据处理
for score in scores:
score["score"] = float(score["score"])
score["running_time"] = float(score["running_time"].replace("ms", ""))
# 分数降序,运行时间升序
scores_sorted = sorted(
scores, key=lambda x: (-x["score"], x["running_time"])
)
# 存储最佳记录
best_scores_by_id = {}
for score in scores_sorted:
student_id = score["id"]
if student_id not in best_scores_by_id:
best_scores_by_id[student_id] = score
# 取前十名
for score in scores:
score["running_time"] = str(score["running_time"]) + "ms"
top_scores = list(best_scores_by_id.values())[:10]
response = jsonify(top_scores)
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Cache-Control", "public, max-age=300")
return response
except Exception as e: except Exception as e:
return jsonify({"error": str(e)}), 500 return jsonify({"error": str(e)}), 500
+70
View File
@@ -0,0 +1,70 @@
def sort_by_time(data, limit=30):
"""
按时间排序
"""
sorted_data = sorted(data, key=lambda x: x["time"], reverse=True)
return sorted_data[:limit] if limit > 0 else sorted_data[::-1][: abs(limit)]
def sort_by_rule(data, sort_by, limit):
"""
根据 sort_by 参数对返回的数据排序
"""
# 规则定义
sort_rules = {
"time": sort_by_time,
"score": sort_by_score,
"id": sort_by_id,
}
# 排序
sorted_data = (
sort_rules[sort_by](data, int(limit)) if limit else sort_rules[sort_by](data)
)
# 恢复格式
for score in sorted_data:
score["running_time"] = f"{score['running_time']}ms"
score["time"] = score["time"].strftime("%Y-%m-%d %H:%M:%S")
score["details"] = ""
return sorted_data
def sort_by_id(data, limit=True):
"""
按学号排序,取对应的最高分,若分数相同则取最短运行时间
"""
# 学号升序,分数降序,运行时间升序
sorted_data = sorted(data, key=lambda x: (x["id"], -x["score"], x["running_time"]))
# 字典去重
unique_students = {}
for record in sorted_data:
id = record["id"]
if id not in unique_students:
unique_students[id] = record
return list(unique_students.values())[
: len(unique_students) if limit == True else abs(limit) : (
1 if limit > 0 else -1
)
]
def sort_by_score(data, limit=10):
"""
处理个人最高分,按分数降序、运行时间升序排序
"""
# 分数降序,运行时间升序
scores_sorted = sorted(data, key=lambda x: (-x["score"], x["running_time"]))
# 字典去重
best_scores_by_id = {}
for score in scores_sorted:
student_id = score["id"]
if student_id not in best_scores_by_id:
best_scores_by_id[student_id] = score
return list(best_scores_by_id.values())[:: 1 if limit > 0 else -1][: abs(limit)]