From dd58307316b14a036fbe923d6255dc3e2d3d0ea4 Mon Sep 17 00:00:00 2001 From: kyomi Date: Sat, 30 Sep 2023 11:23:50 -0300 Subject: [PATCH] feat(apps/contests): save the sent code as a string buffer --- apps/contests/views.py | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/apps/contests/views.py b/apps/contests/views.py index 92ac625..fae0bd9 100644 --- a/apps/contests/views.py +++ b/apps/contests/views.py @@ -1,3 +1,7 @@ +import sys +from io import StringIO +from typing import TYPE_CHECKING + from django.db.models.query import QuerySet from django.http import HttpRequest, HttpResponse from django.shortcuts import get_object_or_404 @@ -5,8 +9,15 @@ from apps.contests.models import Contest +if TYPE_CHECKING: + IndexViewBase = generic.ListView[Contest] + DetailViewBase = generic.DetailView[Contest] +else: + IndexViewBase = generic.ListView + DetailViewBase = generic.DetailView + -class IndexView(generic.ListView[Contest]): +class IndexView(IndexViewBase): template_name = "contests/index.html" context_object_name = "contests" @@ -14,7 +25,7 @@ def get_queryset(self) -> QuerySet[Contest]: return Contest._default_manager.order_by("-start_time")[:5] -class DetailView(generic.DetailView[Contest]): +class DetailView(DetailViewBase): model = Contest template_name = "contests/detail.html" @@ -23,6 +34,18 @@ def send(request: HttpRequest, contest_id: int) -> HttpResponse: contest = get_object_or_404(Contest, pk=contest_id) code = request.POST["code"] - eval(code) + old_stdout = sys.stdout + sys.stdout = buffer = StringIO() + + try: + eval(code) + except Exception as exc: + sys.stdout = old_stdout + return HttpResponse(f"Contest {contest.title} failed.\n{exc}") + + sys.stdout = old_stdout + message = buffer.getvalue() - return HttpResponse(f"Contest {contest.title} ran successfully.") + return HttpResponse( + f"Contest {contest.title} ran successfully.\n{message}" + )