forked from slxmmy999/InfiniteBaseballGrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
140 lines (124 loc) · 4.76 KB
/
server.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
from quart import Quart, request, jsonify, Response
from dotenv import load_dotenv
import os
from motor.motor_asyncio import AsyncIOMotorClient
load_dotenv()
database_connection_string = os.getenv("DB_CONNECTION_STRING")
dev_ip = os.getenv("DEV_IP")
dev = False
if dev:
from GameCategories import GameCategories
from BaseballData import BaseballData
from Database import Database
else:
from server.GameCategories import GameCategories
from server.BaseballData import BaseballData
from server.Database import Database
import datetime
mongo_client = AsyncIOMotorClient(database_connection_string)
db: Database = Database(mongo_client, dev)
app = Quart(__name__)
@app.after_request
async def after_request(response):
if dev:
response.headers["Access-Control-Allow-Origin"] = "http://localhost:3000"
response.headers["Access-Control-Allow-Headers"] = "Content-Type"
return response
else:
allowed_origins = [
"https://www.infiniteimmaculategrid.com",
"https://www.infinitebaseballgrid.com"
]
origin = request.headers.get('Origin')
if origin and origin in allowed_origins:
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Headers"] = "Content-Type"
return response
@app.route("/get_new_grid", methods=["GET"])
async def get_new_grid():
categories: GameCategories = GameCategories()
return jsonify(categories.get_grid())
@app.route("/search_players", methods=["GET"])
async def search_players():
query: str = request.args.get("name")
players: list = await BaseballData.search_players(query)
data: list = players
if len(data) > 0:
if len(data) > 5:
data = data[:5]
players: list = []
for x in range(len(data)):
start: str = ''
end: str = ''
try:
if data[x]['active']:
start = data[x]['mlbDebutDate'][:4]
end = datetime.datetime.now().year
else:
start = data[x]['mlbDebutDate'][:4]
end = data[x]['lastPlayedDate'][:4]
players.append(data[x]["fullName"] + f" | ({start}-{end})")
except KeyError:
players.append(data[x]["fullName"])
return jsonify(players)
return jsonify([])
@app.route("/validate_player", methods=["GET"])
async def validate_player():
query = request.args.get("name")
team1 = request.args.get("team1")
team2 = request.args.get("team2")
start = request.args.get("start")
end = request.args.get("end")
players = await BaseballData.search_players(query)
player = ''
if len(players) > 1:
for x in range(len(players)):
if players[x]["fullName"] == query:
try:
if players[x]['active']:
if start == players[x]['mlbDebutDate'][:4]:
player = players[x]
else:
if start == players[x]['mlbDebutDate'][:4] and end == players[x]['lastPlayedDate'][:4]:
player = players[x]
except KeyError:
continue
else: player = players[0]
teams = BaseballData.get_player_teams(player)
if teams:
if team1 in teams and team2 in teams:
picture = BaseballData.get_player_picture(player)
name = player["fullName"]
id = player['link'].split('/')[-1]
await db.update_matchup(teams=(team1, team2), player=name, id=id)
rarity_score = await db.calculate_rarity_score(teams=(team1, team2), player=name, id=id)
return jsonify({"picture": picture, "name": name, "rarity_score": rarity_score})
# return nothing
return jsonify({})
@app.route("/set_shared_grid", methods=["POST"])
async def set_shared_grid():
data = await request.get_json()
grid = data["grid"]
id = await db.set_shared_grid(grid)
return jsonify({"id": id})
@app.route("/get_shared_grid", methods=["GET"])
async def get_shared_grid():
id = request.args.get("id")
grid = await db.get_shared_grid(id)
if grid == []:
return Response(status=404)
return jsonify(grid)
@app.route("/get_top_players", methods=["POST"])
async def get_top_players():
data = await request.get_json()
grid = data["grid"]
matchups = GameCategories.get_matchups(grid)
top_players = [[], [], []]
for i in range(9):
if len(top_players[i%3]) < 3:
player = await db.get_top_player(matchups[i])
if player:
top_players[i%3].append(player)
return jsonify(top_players)
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)