diff --git a/cig/db.py b/cig/db.py index 0b1c7c3..7d7fd24 100644 --- a/cig/db.py +++ b/cig/db.py @@ -7,6 +7,7 @@ import sqlite3 import dataclasses import pytz +import secrets from typing import Tuple, Optional, List, Iterator from cig.data import Event @@ -45,6 +46,45 @@ def make_record(row: Tuple[int, int, str, str, bool, bool]) -> Registration: return Registrations(event, list(map(make_record, self.conn.execute("SELECT id, event, name, time, admin, deleted FROM registrations WHERE event = ? ORDER BY id ASC", (event.id, ))))) + def submit_quiz(self, *, quiz: str, name: str, correct: int, answers: List[bool]) -> str: + with self.conn: + try: + self.conn.execute("INSERT INTO quiz_participants (quiz, name) VALUES (?, ?)", (quiz, name)) + except sqlite3.IntegrityError: + first = False + else: + first = True + + id = secrets.token_hex(16) + + self.conn.execute("INSERT INTO quiz_answers (id, quiz, correct, answers, first) VALUES (?, ?, ?, ?, ?)", ( + id, + quiz, + correct, + ",".join(str(int(a)) for a in answers), + )) + + return id + + def quiz_submission(self, *, quiz: str, id: str) -> Optional[QuizSubmission]: + with self.conn: + cursor = self.conn.execute("SELECT FROM quiz_answers id, quiz, correct, answers WHERE id = ? AND quiz = ?", (id, quiz)) + row = cursor.fetchone() + return QuizSubmission( + id=row[0], + quiz=row[1], + correct=row[2], + answers=[bool(int(a)) for a in row[3].split(",")], + ) if row is not None else row + + +@dataclasses.dataclass +class QuizSubmission: + id: str + quiz: str + correct: int + answers: List[bool] + @dataclasses.dataclass class Registration: diff --git a/cig/server.py b/cig/server.py index 6a5303d..2c874d5 100644 --- a/cig/server.py +++ b/cig/server.py @@ -222,7 +222,14 @@ async def post_quiz(req: aiohttp.web.Request) -> aiohttp.web.Response: text=cig.view.link_sent(title="Link sent", email_text=email_text if req.app["dev"] else None).render(), content_type="text/html") else: - assert False # XXX + answers = [] + correct = 0 + for i, statement in enumerate(cig.example_quiz.STATEMENTS): + answer = form.get(f"stmt-{i}", "") == "1" + answers.append(int(answer)) + correct += answer == statement.truth + submission = req.app["db"].submit_quiz(correct, answers) + raise aiohttp.web.HTTPFound(location=cig.view.url("complexity", "quiz", submission)) def main(argv: List[str]) -> None: