-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresources.py
59 lines (42 loc) · 1.86 KB
/
resources.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
from typing import Dict, Tuple, List
from functools import lru_cache
from flask import current_app as app, request
from flask_restful import Resource
from random_choice import get_random_choice
class ChoicesResource(Resource):
@lru_cache(maxsize=1)
def get(self) -> Tuple[List[Dict], int]:
sorted_choices = app.choices.get_sorted_ids()
ret = []
for choice_id, choice_name in sorted_choices:
ret.append({'id': choice_id, 'name': choice_name})
return ret, 200
class ChoiceResource(Resource):
def get(self) -> Tuple[Dict, int]:
try:
choice_id = get_random_choice(app.choices.get_max_choice())
except Exception as e:
app.logger.error('Random number API failed with', e)
return {'error': 'cannot get random number'}, 500
choice_name = app.choices.get_choice_name_by_id(choice_id)
return {'id': choice_id, 'name': choice_name}, 200
class RoundResource(Resource):
def post(self) -> Tuple[Dict, int]:
if not request.json or 'player' not in request.json:
return {'error': 'player choice not present'}, 400
player_choice_id = request.json['player']
if not app.choices.choice_id_valid(player_choice_id):
return {'error': 'invalid choice'}, 400
try:
computer_choice_id = get_random_choice(app.choices.get_max_choice())
except Exception as e:
app.logger.error('Random number API failed with', e)
return {'error': 'cannot get random number'}, 500
result = app.choices.decide_game(player_choice_id, computer_choice_id)
if result == -1:
result = 'win'
elif result == 0:
result = 'tie'
else:
result = 'lose'
return {'results': result, 'player': player_choice_id, 'computer': computer_choice_id}, 200