Skip to content

Commit 5bcb97c

Browse files
committed
Improve error handling when contacting quiz API
1 parent c8fb449 commit 5bcb97c

6 files changed

+53
-21
lines changed

create_gform.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def create_google_form(game_obj):
133133

134134
while ask_form_owner:
135135
email = input("\nPlease enter the e-mail address of your Google "
136-
"Account or enter Q to quit:\n")
136+
"Account or enter Q to quit:\n\n")
137137
email = email.lower()
138138

139139
# Quit to main menu if user types Q or quit

create_gform_items.py

-4
Original file line numberDiff line numberDiff line change
@@ -120,10 +120,6 @@ def create_gform_round(round_obj):
120120
for question in questions:
121121
form_items.insert(0, create_gform_question(question))
122122

123-
f = open("test.txt", "a")
124-
f.write(question.get_question() + "\n")
125-
f.close()
126-
127123
form_items.append(create_gform_page_break(round_num, category))
128124

129125
return form_items

create_quiz.py

+31-7
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
from helpers import ask_any_key, ask_yes_no, clear, is_quit
22
import requests
33
import json
4-
import random
54
import urllib.parse
65
from termcolor import cprint
76
from time import sleep
87

9-
CATEGORIES_DATA = json.loads(requests.get(
10-
"https://opentdb.com/api_category.php").text)["trivia_categories"]
118

12-
SESSION_TOKEN = json.loads(requests.get(
13-
"https://opentdb.com/api_token.php?command=request").text)["token"]
9+
def get_category_data():
10+
"""
11+
Makes a call the the Quiz API and returns the list of available categories
12+
"""
13+
result = json.loads(requests.get(
14+
"https://opentdb.com/api_category.php").text)["trivia_categories"]
15+
16+
return result
1417

1518

1619
def create_categories_dict(categories_data):
@@ -30,7 +33,26 @@ def create_categories_dict(categories_data):
3033
return cats_dict
3134

3235

33-
QUIZ_CATEGORIES = create_categories_dict(CATEGORIES_DATA)
36+
def get_session_token():
37+
"""
38+
Makes a call to the Quiz API for a Session token which keeps track of the
39+
questions so the user doesn't receive the same question twice.
40+
"""
41+
result = json.loads(requests.get(
42+
"https://opentdb.com/api_token.php?command=request").text)["token"]
43+
44+
return result
45+
46+
# Quiz API Setup
47+
try:
48+
CATEGORIES_DATA = get_category_data()
49+
QUIZ_CATEGORIES = create_categories_dict(CATEGORIES_DATA)
50+
SESSION_TOKEN = get_session_token()
51+
except Exception:
52+
cprint("🚫 The Quiz API could not be reached!\n", "red")
53+
print("See https://opentdb.com/ \n")
54+
print("Please try again later.")
55+
quit()
3456

3557

3658
def get_quiz_questions(num_qs, cat, diff):
@@ -40,9 +62,11 @@ def get_quiz_questions(num_qs, cat, diff):
4062
question, correct_answer and incorrect_answers
4163
"""
4264

43-
return json.loads(requests.get(
65+
result = json.loads(requests.get(
4466
f"https://opentdb.com/api.php?amount={num_qs}&category={cat}&difficulty={diff}&type=multiple&token={SESSION_TOKEN}&encode=url3986").text)["results"] # noqa
4567

68+
return result
69+
4670

4771
class Game:
4872
"""

gdrive_utility.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414

1515
DRIVE_SERVICE = discovery.build("drive", "v3", credentials=SCOPED_CREDENTIALS)
1616

17+
# Functions adapted from code in the Google Drive API Docs Quickstart Guide:
18+
# https://developers.google.com/drive/api/quickstart/python
19+
1720

1821
def delete_file(file_id):
1922
"""Permanently delete a Google Drive file, skipping the trash.
@@ -89,7 +92,7 @@ def insert_permission(service, file_id, value, role):
8992
return service.permissions().create(
9093
fileId=file_id, body=new_permission).execute()
9194
except errors.HttpError as error:
92-
print(f"An error occurred: {error}")
95+
print(f"🚫 An error occurred: {error}")
9396
return
9497

9598

@@ -137,4 +140,4 @@ def run():
137140
delete_all_files()
138141
continue
139142
else:
140-
continue
143+
continue

helpers.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from os import system, name
22
from time import sleep
33
from datetime import datetime
4+
from termcolor import cprint
45

56
now = datetime.now()
67
current_hour = int(now.strftime("%H"))
@@ -17,7 +18,8 @@ def ask_yes_no(question):
1718
yes = ["yes", "y"]
1819
no = ["no", "n"]
1920

20-
print(f"\n{question} \n\ny/n\n")
21+
print(f"\n{question}")
22+
print(f"\n[Y/n]\n")
2123
while True:
2224
choice = input().lower()
2325
if choice in yes:
@@ -37,7 +39,7 @@ def is_quit(response):
3739
otherwise returns False.
3840
"""
3941
if response.lower() in ["q", "quit"]:
40-
if ask_yes_no("Would you like to return to the Main Menu?"):
42+
if ask_yes_no("Would you like to return to the Main Menu?\n"):
4143
return True
4244
else:
4345
return False
@@ -49,7 +51,8 @@ def ask_any_key():
4951
"""
5052
Ask the user to press any key to return to main menu
5153
"""
52-
input("Press any key to return to Main Menu.")
54+
cprint("Press any key to return to Main Menu.", "white", "on_blue")
55+
input()
5356
return
5457

5558

run.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
if os.path.exists("env.py"):
1212
import env # noqa
1313

14+
# Password for Secret Google Drive Utility
1415
SECRET = os.environ.get("ADMIN")
1516

1617

@@ -69,7 +70,7 @@ def main():
6970
submit their answers!
7071
7172
Enter "Quit" or "Q" at any time to return to the Main Menu.
72-
73+
7374
See this project on GitHub at https://github.com/davidindub/quiz-master
7475
Quiz Master 2022 © David Kelly.
7576
"""]
@@ -85,7 +86,7 @@ def main():
8586
clear()
8687

8788
# Main Menu:
88-
print("Main Menu")
89+
cprint("Main Menu", "white", "on_blue")
8990
print("_________\n")
9091

9192
try:
@@ -126,14 +127,19 @@ def main():
126127

127128
google_quiz = setup_new_quiz()
128129

129-
create_google_form(google_quiz)
130+
try:
131+
create_google_form(google_quiz)
132+
except Exception:
133+
cprint("There was an error with the Google Form API\n\n", "red")
134+
print("Please try again later.")
130135

131136
continue
132137
if response == 4:
133138
clear()
134139
tprint("HELP", font="o8")
135140
print(help_text[0])
136-
input("Press any key to read more.\n")
141+
cprint("Press any key to read more.", "white", "on_blue")
142+
input()
137143
clear()
138144
print(help_text[1])
139145
ask_any_key()

0 commit comments

Comments
 (0)