From 27e77368c82af11be22914206bfd6c174adf7307 Mon Sep 17 00:00:00 2001 From: Kevin Chung Date: Wed, 9 Feb 2022 21:03:44 -0500 Subject: [PATCH] Improve speed of the ChallengeSolves API endpoint (#2046) * Improve speed of the ChallengeSolves API (`/api/v1/challenges/[challenge_id]/solves`) endpoint --- CHANGELOG.md | 4 ++++ CTFd/api/v1/challenges.py | 11 +++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d2afcb3..bf330eb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# UNRELEASED + +- Improved speed of the `/api/v1/challenges/[challenge_id]/solves` endpoint + # 3.4.0 / 2021-08-11 **General** diff --git a/CTFd/api/v1/challenges.py b/CTFd/api/v1/challenges.py index e5594999..8d141a1c 100644 --- a/CTFd/api/v1/challenges.py +++ b/CTFd/api/v1/challenges.py @@ -764,8 +764,13 @@ class ChallengeSolves(Resource): Model = get_model() + # Note that we specifically query for the Solves.account.name + # attribute here because it is faster than having SQLAlchemy + # query for the attribute directly and it's unknown what the + # affects of changing the relationship lazy attribute would be solves = ( - Solves.query.join(Model, Solves.account_id == Model.id) + Solves.query.add_columns(Model.name.label("account_name")) + .join(Model, Solves.account_id == Model.id) .filter( Solves.challenge_id == challenge_id, Model.banned == False, @@ -782,10 +787,12 @@ class ChallengeSolves(Resource): solves = solves.filter(Solves.date < dt) for solve in solves: + # Seperate out the account name and the Solve object from the SQLAlchemy tuple + solve, account_name = solve response.append( { "account_id": solve.account_id, - "name": solve.account.name, + "name": account_name, "date": isoformat(solve.date), "account_url": generate_account_url(account_id=solve.account_id), }