-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
344 lines (248 loc) · 10.8 KB
/
app.py
File metadata and controls
344 lines (248 loc) · 10.8 KB
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
import os
from flask import Flask, render_template, request, flash, redirect, session, jsonify, g
from flask_debugtoolbar import DebugToolbarExtension
from sqlalchemy.exc import IntegrityError
from secrets import API_KEY_SECRETS_FILE
import requests
from datetime import datetime, date
from ratelimit import limits, sleep_and_retry
from forms import UserAddForm, UserEditForm, LoginForm, PredictionsForm
from models import db, connect_db, User, Bio, Prediction_top, Prediction_bottom, Prediction_manager, Team, Season_league, Team_info, Results_all, Results_home, Results_away, League_standing, Fixture
from populate_scripts import populate_standings_table
from populate_scripts import populate_results_all_table
today = date.today()
d1 = today.strftime("%Y-%m-%d")
FIFTEEN_MINUTES = 900
FIVE_MINUTES = 300
CURR_USER_KEY = "curr_user"
app = Flask(__name__)
API_BASE_URL = "https://api-football-v1.p.rapidapi.com/v2"
app.config['SQLALCHEMY_DATABASE_URI'] = (
os.environ.get('DATABASE_URL', 'postgres:///matchday'))
app.config['API_KEY'] = (os.environ.get('API_KEY', API_KEY_SECRETS_FILE))
API_KEY = app.config['API_KEY']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', "it's a secret")
# toolbar = DebugToolbarExtension(app)
# 3456 is the API-Football id for the 2021-22 English Premier League
# 2790 is the API-Football id for the 2020-21 English Premier League
LEAGUE2020 = 2790
LEAGUE2021 = 3456
LEAGUE_ID = LEAGUE2021
connect_db(app)
#update league table details in database
#comment this function call out before running tests
populate_standings_table()
populate_results_all_table()
@app.before_request
def add_user_to_g():
"""If we're logged in, add curr user to Flask global."""
if CURR_USER_KEY in session:
g.user = User.query.get(session[CURR_USER_KEY])
else:
g.user = None
def do_login(user):
"""Log in user."""
session[CURR_USER_KEY] = user.id
def do_logout():
"""Logout user."""
if CURR_USER_KEY in session:
del session[CURR_USER_KEY]
@app.route("/leagues")
def getLeagues():
"""show available leagues"""
url = f"https://api-football-v1.p.rapidapi.com/v2/leagues"
headers = {
'x-rapidapi-key': API_KEY,
'x-rapidapi-host': "api-football-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
print("*******************")
print (response)
data = response.json()
return data
@app.route("/")
def homepage():
"""Show homepage."""
return render_template("index.html")
@app.route('/signup', methods=["GET", "POST"])
def signup():
"""Handle user signup.
Create new user and add to DB. Redirect to home page.
If form not valid, present form.
If the there already is a user with that username: flash message
and re-present form.
"""
if CURR_USER_KEY in session:
del session[CURR_USER_KEY]
form = UserAddForm()
# the two lines below are not working; should give a drop down list of team_ids in the form
#(next step is show team_name)
fave_team_list = []
teams = db.session.query(League_standing.team_id, Team.team_name).join(Team).all()
for (id, name) in teams:
fave_team_list.append(name)
team_choices = [(team, team) for team in fave_team_list]
form.fave_team.choices = team_choices
if form.validate_on_submit():
user = User.signup(
username = form.username.data,
first_name = form.first_name.data,
last_name = form.last_name.data,
password = form.password.data,
fave_team = form.fave_team.data,
email = form.email.data
)
db.session.commit()
do_login(user)
return redirect("/user/profile")
else:
return render_template('signup.html', form=form)
@app.route('/user/profile')
def profile_page():
"""Present details of user's profile"""
if not g.user:
flash("Sorry, you are not authorised to view this page", "danger")
return redirect("/")
return render_template('user_profile.html')
@app.route('/login', methods=["GET", "POST"])
def login():
"""Handle login.
Present login form
Check validity of username and password
If details not valid, flash info message and re-present form.
"""
form = LoginForm()
if form.validate_on_submit():
user = User.authenticate(form.username.data,
form.password.data)
if user:
do_login(user)
return redirect('/home')
flash("Sorry, you're details don't match", 'danger')
return render_template('login.html', form=form)
@app.route('/logout')
def logout():
"""Logout user."""
do_logout()
flash(f"Thanks for visiting Matchday. You are now logged out", "success")
return redirect('/')
@app.route('/home')
def home_page():
"""user home page displaying league standing for fave team and the next 5 games for team"""
if not g.user:
flash("Sorry, you are not authorised to view this page", 'danger')
return redirect("/")
team = Team.query.filter_by(team_name = g.user.fave_team).all()
results = Results_all.query.filter_by(team_id = team[0].team_id).all()
results_data = results[0]
league = League_standing.query.filter_by(team_id = team[0].team_id).all()
league_data = league[0]
record = League_standing.query.filter_by(team_id = team[0].team_id).all()
users_team = Team.query.filter_by(team_name = g.user.fave_team).all()
url = f"https://api-football-v1.p.rapidapi.com/v2/fixtures/team/{users_team[0].team_id}/next/5"
headers = {
'x-rapidapi-key': API_KEY,
'x-rapidapi-host': "api-football-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
data = response.json()
future_games = data['api']['fixtures']
return render_template('home.html', results_data=results_data, league_data=league_data, future_games = future_games, record=record)
@limits(calls = 1, period = FIVE_MINUTES)
@app.route('/user/recent_results')
def show_recent_results():
"""Show last five results in league"""
if not g.user:
flash("Sorry, you are not authorised to view this page", "danger")
return redirect("/")
url = f"https://api-football-v1.p.rapidapi.com/v2/fixtures/league/{LEAGUE_ID}/last/5"
headers = {
'x-rapidapi-key': API_KEY,
'x-rapidapi-host': "api-football-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
data = response.json()
results = data['api']['fixtures']
return render_template('recent_results.html', results = results)
@app.route('/user/<int:user_id>/predictions', methods=['GET', 'POST'])
def predictions(user_id):
"""Record season predictions from user"""
if not g.user:
flash("Sorry, you are not authorised to view this page", "danger")
return redirect("/")
form = PredictionsForm()
user = User.query.get_or_404(user_id)
if form.validate_on_submit():
prediction_top = Prediction_top(first = form.top_team.data,
second = form.second_place.data,
third = form.third_place.data,
fourth = form.fourth_place.data,
user_id = user_id)
prediction_bottom = Prediction_bottom(last = form.bottom_team.data,
last_less_one = form.second_from_bottom.data,
last_less_two = form.third_from_bottom.data,
user_id = user_id)
prediction_manager = Prediction_manager(first = form.manager_one.data,
second = form.manager_two.data,
user_id = user_id)
db.session.add(prediction_top)
db.session.add(prediction_bottom)
db.session.add(prediction_manager)
db.session.commit()
return redirect('/')
return render_template('predictions.html', form=form, user=user)
@app.route('/user/<int:user_id>/predictions/show')
def predictions_show(user_id):
"""Show user's predictions for the season"""
if not g.user:
flash("Sorry, you are not authorised to view this page", "danger")
return redirect("/")
if Prediction_top.query.filter_by(user_id = g.user.id).all() == [] or Prediction_bottom.query.filter_by(user_id = g.user.id).all() == [] or Prediction_manager.query.filter_by(user_id = g.user.id).all() == []:
flash("Please enter your predictions", "info")
return redirect(f"/user/{user_id}/predictions")
predictions_top = Prediction_top.query.filter_by(user_id = user_id)
predictions_bottom = Prediction_bottom.query.filter_by(user_id = user_id)
predictions_manager = Prediction_manager.query.filter_by(user_id = user_id)
return render_template('predictions_show.html', predictions_top = predictions_top, predictions_bottom = predictions_bottom, predictions_manager = predictions_manager)
@app.route('/leaguetable')
def show_league_table():
"""Show current league table"""
league = League_standing.query.all()
return render_template('league_table.html', league = league)
@limits(calls = 1, period = FIVE_MINUTES)
@app.route('/fixtures')
def show_upcoming_fixtures():
if not g.user:
flash("Sorry, you are not authorised to view this page", "danger")
return redirect("/")
url = f"https://api-football-v1.p.rapidapi.com/v2/fixtures/league/{LEAGUE_ID}/next/5"
headers = {
'x-rapidapi-key': API_KEY,
'x-rapidapi-host': "api-football-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
data = response.json()
fixtures = data['api']['fixtures']
return render_template('league_fixtures.html', fixtures = fixtures)
@limits(calls = 3, period = FIVE_MINUTES)
@app.route('/user/live')
def show_live_games():
"""Show scheduled/live games for the day """
if not g.user:
flash("Sorry, you are not authorised to view this page", "danger")
return redirect("/")
d_today = today.strftime("%d-%b-%Y")
url = f"https://api-football-v1.p.rapidapi.com/v2/fixtures/league/{LEAGUE_ID}/{d1}"
headers = {
'x-rapidapi-key': API_KEY,
'x-rapidapi-host': "api-football-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
data = response.json()
if data['api']['results'] == 0:
return render_template('live_no_games.html')
fixtures = data['api']['fixtures']
return render_template("live.html", fixtures = fixtures, d_today = d_today)