forked from gblanktest/squiz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuiz.py
49 lines (40 loc) · 1.7 KB
/
Quiz.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import json
import requests
from html import unescape
from Question import Question
class Quiz():
@classmethod
def get_categories(cls) -> dict:
with open("quiz_categories.json","r") as readable_file:
raw_content = readable_file.readline()
return json.loads(raw_content)
@classmethod
def get_questions(cls, category: str, amount: int = 10) -> list:
try:
api_url = "https://opentdb.com/api.php"
response = requests.get(f"{api_url}?type=multiple&amount={amount}&category={category}")
content = json.loads(response.text)
cls.decode_questions(content["results"])
return content["results"]
except Exception:
return []
@classmethod
def decode_questions(cls, questions: list) -> None:
for question in questions:
question["question"] = unescape(question["question"])
question["correct_answer"] = unescape(question["correct_answer"])
for index, option in enumerate(question["incorrect_answers"]):
question["incorrect_answers"][index] = unescape(option)
def __init__(self) -> None:
self.questions: list = []
self.score: int = 0
def add_raw_questions(self, raw_questions: list) -> None:
for raw_question in raw_questions:
options = []
for option in raw_question["incorrect_answers"]:
options.append(option)
title = raw_question["question"]
answer = raw_question["correct_answer"]
options.append(answer)
question = Question(title, options, answer)
self.questions.append(question)