Skip to content

Commit

Permalink
write quiz submission crud
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasf committed Oct 23, 2020
1 parent bf057af commit 49c88ab
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
40 changes: 40 additions & 0 deletions cig/db.py
Expand Up @@ -7,6 +7,7 @@
import sqlite3
import dataclasses
import pytz
import secrets

from typing import Tuple, Optional, List, Iterator
from cig.data import Event
Expand Down Expand Up @@ -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:
Expand Down
9 changes: 8 additions & 1 deletion cig/server.py
Expand Up @@ -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:
Expand Down

0 comments on commit 49c88ab

Please sign in to comment.