Skip to content
This repository has been archived by the owner on Jan 3, 2024. It is now read-only.

Commit

Permalink
feat(apps/contests): save the sent code as a string buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
bitterteriyaki committed Sep 30, 2023
1 parent dcea9ca commit dd58307
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions apps/contests/views.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
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
from django.views import generic

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"

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"

Expand All @@ -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}"
)

0 comments on commit dd58307

Please sign in to comment.