-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathleaderboard.py
172 lines (138 loc) · 4.07 KB
/
leaderboard.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
import dataclasses
import textwrap
import redis
from quart import Quart, g, abort, request
from quart_schema import QuartSchema, RequestSchemaValidationError, validate_request
import time
import requests
import socket
app = Quart(__name__)
QuartSchema(app)
@dataclasses.dataclass
class GameData:
game_id: str
username: str
num_of_guesses: int
win: bool
# Register with Game service
@app.before_serving
def register_callback():
error = True
while error:
try:
hostname = socket.getfqdn()
time.sleep(2)
url = f"http://{hostname}/leaderboard/add"
data = {"url": url}
r = requests.post(url='http://localhost:5100/game/webhook', json=data)
print(r.status_code)
if r.status_code == 200 or r.status_code == 409:
error = False
else:
time.sleep(2)
print("retrying...")
error = True
except requests.exceptions.HTTPError:
time.sleep(2)
print("retrying...")
error = True
# Handle bad routes/errors
@app.errorhandler(404)
def not_found(e):
return {"error": "404 The resource could not be found"}, 404
@app.errorhandler(RequestSchemaValidationError)
def bad_request(e):
return {"error": str(e.validation_error)}, 400
@app.errorhandler(409)
def conflict(e):
return {"error": str(e)}, 409
@app.errorhandler(401)
def unauthorize(e):
return str(e), 401, {"WWW-Authenticate": 'Basic realm=User Login'}
def get_redis_db():
r = redis.Redis(host='localhost', port=6379, db=0)
return r
def get_score(guesses, win):
if not win:
return 0.0
elif guesses == 1:
return 6.0
elif guesses == 2:
return 5.0
elif guesses == 3:
return 4.0
elif guesses == 4:
return 3.0
elif guesses == 5:
return 2.0
elif guesses == 6:
return 1.0
else:
return 0.0
# Leaderboard
@app.route("/leaderboard/", methods=["GET"])
def leaderboard():
"""Leader Board Routes"""
# r = redis.Redis(host='localhost', port=6379, db=0)
return textwrap.dedent( """<h1>Welcome to Leaderboard service</h1>
<p>Vu Diep</p>
""")
@app.route("/leaderboard/add", methods=["POST"])
@validate_request(GameData)
async def add_game(data):
"""ADD a game result"""
game_data = dataclasses.asdict(data)
game_id = game_data["game_id"]
username = game_data["username"]
win = game_data["win"]
num_of_guesses = game_data["num_of_guesses"]
r = get_redis_db()
# Set data for a game
r.hset(game_id, "win", int(win))
r.hset(game_id, "username", username)
r.hset(game_id, "num_of_guesses", num_of_guesses)
# Average Score
r.hincrby(username, "games")
current_score = r.hget(username, "score")
game_score = get_score(num_of_guesses, win)
no_of_games = r.hget(username, "games")
if current_score is not None:
current_score = current_score.decode("utf-8")
else:
current_score = 0
if no_of_games is not None:
no_of_games = no_of_games.decode("utf-8")
if float(no_of_games) > 1:
no_of_games = 2
else:
no_of_games = 1
else:
no_of_games = 1
print(game_score)
print(current_score)
print(no_of_games)
avg = ((float(current_score) + float(game_score))) / float(no_of_games)
r.hset(username, "score", avg)
print(avg)
# Set data for user
r.zadd("players", {username: avg})
return {
"game_id": game_id,
"username": username,
"win": win,
"num_of_guesses": num_of_guesses
}
@app.route("/leaderboard/players", methods=["GET"])
async def get_user():
"""GET TOP 10 result"""
r = get_redis_db()
arr = r.zrevrange("players", 0, -1, withscores=True)
top_players = {}
i = 0
print(arr)
while i < len(arr) and i < 10:
player = arr[i]
top_players[i+1] = player[0].decode("utf-8") + " - " + str(player[1])
i += 1
print(top_players)
return top_players