-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
77 lines (59 loc) · 2.71 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
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
import json
from Player import Player
from Score import Score
import datetime
import time
from ScoresHelper import *
class PlayersListHandler(webapp.RequestHandler):
DEFAULT_PLAYER_NAMES = ["Player 1", "Player 2", "Player 3", "Player 4", "Player 5", "Player 6"]
def get(self):
# Create default players if none exist
q = db.Query(Player)
if q.count() == 0:
for pname in self.DEFAULT_PLAYER_NAMES: Player(name=pname).put()
players = [{'name' : p.name, 'id' : p.key().id_or_name()} for p in Player.all()]
self.response.out.write(json.dumps(players))
class NewScoreHandler(webapp.RequestHandler):
def post(self):
req = json.loads(self.request.body)
score = int(req['score'])
playerId = int(req['playerId'])
player = db.Key.from_path('Player', playerId)
Score(player=player, points=score).put()
scoresHelper = ScoresHelper(playerId)
scoresHelper.clearCache()
class PlayerScoreListHandler(webapp.RequestHandler):
def get(self):
playerId = int(self.request.get('playerId'))
maxResults = int(self.request.get('maxScores'))
player = db.get(db.Key.from_path('Player', playerId))
results = player.scores.order('-date').fetch(maxResults)
scores = [{'date' : time.mktime(s.date.timetuple()), 'points' : s.points} for s in results]
stats = {}
# 14 day stats
scoresHelper = ScoresHelper(playerId)
if scoresHelper.hasScores():
stats['max-14-day'] = scoresHelper.get14DayMax()
stats['mean-14-day'] = scoresHelper.get14DayMean()
stats['count-14-day'] = scoresHelper.count14DayScores()
response = {'scores' : scores, 'stats' : stats}
self.response.out.write(json.dumps(response));
class RankingsHandler(webapp.RequestHandler):
def get(self):
rankings = Rankings.getRankings()
keyMappings = {ScoreType.Mean14Day : 'mean-14-day', ScoreType.Max14Day : 'max-14-day', ScoreType.Count14Day : 'count-14-day'}
responseRankings = {}
for scoreType in ScoreType.types():
if keyMappings[scoreType] is not None:
responseRankings[keyMappings[scoreType]] = rankings[scoreType]
self.response.out.write(json.dumps(responseRankings));
application = webapp.WSGIApplication([('/api/players', PlayersListHandler),
('/api/scores/new', NewScoreHandler),
('/api/scores/player', PlayerScoreListHandler),
('/api/scores/rankings', RankingsHandler),
],
debug=True)