/
api.py
497 lines (408 loc) · 19.9 KB
/
api.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
"""api.py - Create and configure the Game API exposing the resources.
This can also contain game logic. For more complex games it would be wise to
move game logic to another file. Ideally the API will be simple, concerned
primarily with communication to/from the API's users."""
import logging
import endpoints
from protorpc import remote, messages, message_types
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from models import User, Question, Turn, TriviaGame, GameSummary, Score
from models import QuestionForm, TriviaQuestionForm, ClueForm, TriviaGameForm,\
NewTriviaGameForm, GameSummaryForm, GameSummaryForms, GameDetailForm, \
GameDetailForms, TriviaGameForms, DataForm, ScoreForm, ScoreForms, \
RankForm, RankForms, StringMessage
from utils import get_by_urlsafe, getFirstKey
NEW_TRIVIA_GAME_REQUEST = endpoints.ResourceContainer(NewTriviaGameForm)
GET_TRIVIA_GAME_REQUEST = endpoints.ResourceContainer(
urlsafe_trivia_game_key=messages.StringField(1),)
NEW_QUESTION_REQUEST = endpoints.ResourceContainer(QuestionForm)
GET_QUESTION_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,)
GENERIC_GET_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,)
HI_SCORE_GET_REQUEST = endpoints.ResourceContainer(
result_num=messages.IntegerField(1, required=False, default=0),)
TAKE_TURN_REQUEST = endpoints.ResourceContainer(
urlsafe_trivia_game_key=messages.StringField(1),
ans=messages.StringField(2),)
GET_CLUE_REQUEST = endpoints.ResourceContainer(
urlsafe_trivia_game_key=messages.StringField(1),)
ANSWER_QUESTION_REQUEST = endpoints.ResourceContainer(
urlsafe_question_key=messages.StringField(1),
answer=messages.StringField(2),)
USER_REQUEST = endpoints.ResourceContainer(user_name=messages.StringField(1),
email=messages.StringField(2))
MEMCACHE_CORRECT_ANSWER_AVERAGE = 'CORRECT_ANSWER_AVERAGE'
@endpoints.api(name='trivia', version='v1')
class TriviaApi(remote.Service):
"""Trivia API"""
@endpoints.method(request_message=USER_REQUEST,
response_message=StringMessage,
path='user',
name='create_user',
http_method='POST')
def create_user(self, request):
"""Create a User. Requires a unique username"""
if User.query(User.name == request.user_name).get():
raise endpoints.ConflictException(
'A User with that name already exists!')
user = User(name=request.user_name, email=request.email)
user.put()
# Create an associated Score for this user
score = Score(user=user.key)
score.put()
return StringMessage(message='User {} created!'.format(
request.user_name))
@staticmethod
def _getPlayerReminder(game, name):
clues_used = game.get_latest_turn().get().clues_used
q_key = game.get_current_question()
question = q_key.get()
(ansA, ansB, ansC, ansD) = list(question.answers.values())
body = "Hi {},\n".format(name)
body += "You started a trivia game, but you haven't "
body += "answered a quesion in over an hour.\n"
body += "Why not come back and try to finish your "
body += "game, you can always ask for a clue "
body += "if you need one.\n"
body += "If you really don't want to finish, you "
body += "can cancel. \n"
body += "Here is where your game stands: "
body += "Question: {}".format(question.question)
body += "A.{}\nB.{}\nC.{}\nD.{}\n".format(ansA, ansB, ansC, ansD)
body += "You have used {} clues\n".format(clues_used)
body += "You have {} more questions\n".format(game.rounds_remaining)
return body
@staticmethod
def _cache_average_correct_per_game():
"""Populates memcache with the average correct answers per game"""
games = TriviaGame.query(TriviaGame.game_over == True).fetch()
if games:
correct_count = 0
count = len(games)
for game in games:
turns = game.turn_keys
total_correct_answers = sum([turn.get().is_correct
for turn in turns])
average = float(total_correct_answers)/count
memcache.set(MEMCACHE_CORRECT_ANSWER_AVERAGE,
'Average correct answer \
per game: {:.2f}'.format(average))
@endpoints.method(request_message=NEW_TRIVIA_GAME_REQUEST,
response_message=TriviaGameForm,
path='triviagame',
name='new_trivia_game',
http_method='POST')
def new_triva_game(self, request):
"""Creates new trivia game"""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
game = TriviaGame.new_game(user.key, request.rounds)
# Use a task queue to update the average correct answers per game.
# This operation is not needed to complete the creation of a new game
# so it is performed out of sequence.
taskqueue.add(url='/tasks/cache_average_correct_per_game')
return game.to_form('Good luck playing the Trivia Game!')
@endpoints.method(request_message=GET_TRIVIA_GAME_REQUEST,
response_message=TriviaGameForm,
path='triviagame/{urlsafe_trivia_game_key}',
name='get_trivia_game',
http_method='GET')
def get_trivia_game(self, request):
"""Return the current game state. Requires urlsafe_trivia_game_key"""
game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame)
if game:
user_key = game.user
question_key = game.get_question_from_pool()
if question_key:
if len(game.turn_keys) == 0:
# Create a new turn
turn = Turn.new_turn(game.key, user_key, question_key)
game.remove_question_from_pool(question_key)
game.register_turn(turn.key)
# Get a question object
question = get_by_urlsafe(question_key.urlsafe(), Question)
return game.to_form(question.question,
question.answers.values())
else:
game.clear_game()
g_form = game.to_form('No available questions, Game aborted!')
game.key.delete()
return g_form
else:
raise endpoints.NotFoundException('Game not found!')
@endpoints.method(request_message=TAKE_TURN_REQUEST,
response_message=TriviaGameForm,
path='triviagame/{urlsafe_trivia_game_key}/answer/{ans}',
name='take_turn',
http_method='PUT')
def take_turn(self, request):
""" Take turn by answering a question in the triviagame. Requires
urlsafe_trivia_game_key and answer."""
# Get the game in question
game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame)
if game.game_over:
return game.to_form('Game already over!')
game.rounds_remaining -= 1
turn_key = game.get_latest_turn()
if not turn_key:
return game.to_form('Please get a game before taking a turn!')
turn = get_by_urlsafe(turn_key.urlsafe(), Turn)
question = get_by_urlsafe(turn.question_key.urlsafe(), Question)
if question.is_correct_answer(request.ans):
result = "You are correct. "
turn.set_correct_answer()
points = question.value
if turn.clues_used != 0:
points -= 2**turn.clues_used
turn.set_points(points)
game.update_current_score(points)
else:
result = "You are not correct. "
turn.set_answer_given(request.ans)
turn.set_finished()
turn.put()
if game.rounds_remaining < 1:
game.end_game()
return game.to_form(result + ' Game over!')
else:
user_key = game.user
question_key = game.get_question_from_pool()
if question_key:
# Create a new turn
turn = Turn.new_turn(game.key, user_key, question_key)
game.remove_question_from_pool(question_key)
game.register_turn(turn.key)
# Get a question object
question = get_by_urlsafe(question_key.urlsafe(), Question)
game.put()
message = result + question.question
return game.to_form(message, question.answers.values())
else:
game.end_game()
return game.to_form(result + ' No more questions, Game Over!')
@endpoints.method(request_message=NEW_QUESTION_REQUEST,
response_message=QuestionForm,
path='question/create',
name='create_question',
http_method='POST')
def create_question(self, request):
"""Creates a question that can be used in the trivia game"""
question = request.question
answers = {'correct': request.correct,
'wrong1': request.wrong1,
'wrong2': request.wrong2,
'wrong3': request.wrong3}
clues = [request.clue1, request.clue2]
newQuestion = Question.new_question(question, answers, clues)
return newQuestion.to_form()
@endpoints.method(request_message=GET_CLUE_REQUEST,
response_message=StringMessage,
path='triviagame/{urlsafe_trivia_game_key}/clue',
name='get_clue',
http_method='GET')
def get_clue(self, request):
"""Retrieve a clue for a question. Requires urlsafe_trivia_game_key"""
game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame)
if game:
if game.game_over:
return StringMessage(message='Game already over!')
turn_key = game.get_latest_turn()
turn = get_by_urlsafe(turn_key.urlsafe(), Turn)
question = get_by_urlsafe(turn.question_key.urlsafe(), Question)
if turn.clues_used < 2:
clue = question.clues[turn.clues_used]
turn.used_clue()
turn.put()
else:
clue = 'You have used up all of your clues!'
return StringMessage(message=clue)
else:
raise endpoints.NotFoundException('Game not found!')
@endpoints.method(request_message=GET_QUESTION_REQUEST,
response_message=TriviaQuestionForm,
path='question/retrieve',
name='get_question',
http_method='GET')
def get_question(self, request):
"""Retrieve a question."""
q = Question.query()
question = q.get()
if question:
return question.to_trivia_form()
else:
raise endpoints.NotFoundException('No question not found!')
@endpoints.method(request_message=ANSWER_QUESTION_REQUEST,
response_message=StringMessage,
path='question/{urlsafe_question_key}/answer/{answer}',
name='answer_question',
http_method='POST')
def answer_question(self, request):
"""Answer a question and check correctness. Requires urlsafe_question_key
and answer"""
wsqk = request.urlsafe_question_key
question = get_by_urlsafe(wsqk, Question)
if question.is_correct_answer(request.answer):
result = "is correct."
else:
result = "is not correct."
return StringMessage(message='Your answer to {} {}!'.format(
question.question, result))
@endpoints.method(request_message=GET_TRIVIA_GAME_REQUEST,
response_message=GameDetailForms,
path='triviagame/{urlsafe_trivia_game_key}/details',
name='get_trivia_game_history',
http_method='GET')
def get_trivia_game_history(self, request):
"""Retrieve the history for one completed game. Requires
urlsafe_trivia_game_key."""
game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame)
if game:
q = GameSummary.query()
game_summary = q.filter(GameSummary.trivia_game == game.key).get()
if game_summary:
aggregates = game_summary.aggregate_data()
return GameDetailForms(user_name=game_summary.user.get().name,
items=game_summary.to_detail_form(),
total_correct=aggregates[1],
total_incorrect=aggregates[2],
total_clues_used=aggregates[3],
total_points=aggregates[0])
else:
raise endpoints.NotFoundException('Game not found!')
else:
raise endpoints.NotFoundException('Game not found!')
@endpoints.method(request_message=USER_REQUEST,
response_message=GameSummaryForms,
path='triviagame/user/{user_name}/summary',
name='get_user_trivia_game_summary',
http_method='GET')
def get_user_trivia_game_summary(self, request):
"""Returns a summary of an individual User's games. This
includes the user name, date, number of questions answered,
number answered correctly and incorrectly, the number of clues
used and the total score for the game. Requires user_name."""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
sums = GameSummary.query(GameSummary.user == user.key)
return GameSummaryForms(items=[smy.to_summary_form() for smy in sums])
@endpoints.method(request_message=USER_REQUEST,
response_message=GameDetailForms,
path='triviagame/user/{user_name}/detail',
name='get_user_trivia_game_detail',
http_method='GET')
def get_user_trivia_game_detail(self, request):
"""Returns a detailed listing of an individual User's games. This
includes all questions for each game, the given answer for each
question, whether the given answer correct or not, how many clues
were used to answer each question, how many points were awarded
for each question and the date for the question.
Requires user_name. """
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
items = []
data = [0, 0, 0, 0]
summaries = GameSummary.query(GameSummary.user == user.key)
for summary in summaries:
items.extend(summary.to_detail_form())
data = [x + y for x, y in zip(data, summary.aggregate_data())]
return GameDetailForms(user_name=user.name, items=items,
total_correct=data[1],
total_incorrect=data[2],
total_clues_used=data[3],
total_points=data[0])
@endpoints.method(request_message=USER_REQUEST,
response_message=TriviaGameForms,
path='triviagame/user/{user_name}/active',
name='get_user_games',
http_method='GET')
def get_user_games(self, request):
"""Returns the active games of a user. Requires user_name"""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
games = TriviaGame.query() \
.filter(TriviaGame.user == user.key) \
.filter(TriviaGame.game_over == False).fetch()
items = []
for game in games:
question = game.get_current_question().get()
question_asked = question.question
answers = question.answers.values()
items.append(game.to_form(question_asked, answers))
return TriviaGameForms(items=items)
@endpoints.method(request_message=GET_TRIVIA_GAME_REQUEST,
response_message=StringMessage,
path='triviagame/{urlsafe_trivia_game_key}/cancel',
name='cancel_trivia_game',
http_method='DELETE')
def cancel_trivia_game(self, request):
"""Cancel an active game. Requires urlsafe_trivia_game_key."""
game = get_by_urlsafe(request.urlsafe_trivia_game_key, TriviaGame)
if game:
if game.game_over:
return StringMessage(message='Game is over, cannot cancel!')
game.clear_game()
game.key.delete()
return StringMessage(message='Game cancelled!')
else:
raise endpoints.NotFoundException('Game not found!')
@endpoints.method(request_message=USER_REQUEST,
response_message=ScoreForm,
path='scores/user/{user_name}',
name='get_user_score',
http_method='GET')
def get_user_score(self, request):
"""Returns an individual User's scores. Requires user_name."""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name does not exist!')
score = Score.query(Score.user == user.key).get()
if score:
return score.to_score_form()
else:
raise endpoints.NotFoundException('Score not found!')
@endpoints.method(request_message=HI_SCORE_GET_REQUEST,
response_message=ScoreForms,
path='scores/highscores/{result_num}',
name='get_high_scores',
http_method='GET')
def get_high_scores(self, request):
"""Retrieve the high scores to date. Optionally accepts
result_num which is the number of results wanted."""
sq = Score.query().order(-Score.score)
if request.result_num > 0:
scores = sq.fetch(limit=request.result_num)
else:
scores = sq.fetch()
return ScoreForms(items=[score.to_score_form() for score in scores])
@endpoints.method(request_message=GENERIC_GET_REQUEST,
response_message=RankForms,
path='user/rankings',
name='get_rankings',
http_method='GET')
def get_rankings(self, request):
"""Retrieve the user rankings to date."""
s = Score.query()
scores = s.order(-Score.score).order(Score.clues_used).fetch()
ranks = []
for score in scores:
name = score.user.get().name
denominator = float(score.num_correct + score.num_incorrect)
factor = score.num_correct/denominator
rank = round((10 * score.score * factor)) - score.clues_used
tup = (name, rank)
ranks.append(tup)
ranks = sorted(ranks, reverse=True, key=getFirstKey)
rankings = [RankForm(name=rank[0], ranking=rank[1]) for rank in ranks]
return RankForms(items=rankings)
api = endpoints.api_server([TriviaApi])