-
Notifications
You must be signed in to change notification settings - Fork 11
/
utils.py
executable file
·91 lines (66 loc) · 1.99 KB
/
utils.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import flask
from werkzeug.exceptions import abort
from sql import get_sql
def get_random_answer():
"""
Retrieves a random answer from the answerList table
:rtype: tuple
:returns: A tuple of len 2: (word_id, word)
"""
con, cur = get_sql()
word_id, word = cur.execute(
"""SELECT id, word FROM answerList ORDER BY RANDOM() LIMIT 1"""
).fetchone()
return word_id, word
def get_answer_info(word_id):
"""
Retrieves an answer from answerList that matches word_id
:rtype: str
"""
con, cur = get_sql()
word = cur.execute(
"""SELECT word FROM answerList WHERE id = (?)""", (word_id,)
).fetchone()
return word
def word_is_valid(word):
"""
Checks if a word is contained in the wordList table.
:rtype: bool
:returns: True if it's in the table, otherwise false
"""
con, cur = get_sql()
cur.execute("""SELECT word FROM wordList WHERE word = (?)""", (word,))
return bool(cur.fetchone())
def id_or_400(request: flask.Request):
"""
Returns the game id associated with the request. On failure, forces a 400 error response.
:rtype: int
"""
try:
game_id = request.get_json(force=True)["id"]
key = request.get_json(force=True)["key"]
con, cur = get_sql()
cur.execute("""SELECT key FROM game WHERE key = (?)""", (key,))
assert cur.fetchone()[0] == key
con.close()
return game_id
except (AssertionError, KeyError, TypeError):
abort(400)
def set_finished(game_id):
"""
Changes the status of a game to finished
"""
con, cur = get_sql()
cur.execute("""UPDATE game SET finished = true WHERE id = (?) """, (game_id,))
con.commit()
con.close()
def get_game_answer(game_id):
"""
Get's the answer associated with a game
:rtype: str
"""
con, cur = get_sql()
cur.execute("""SELECT word FROM game WHERE id = (?)""", (game_id,))
answer = cur.fetchone()
con.close()
return answer[0]