· 6 years ago · Apr 12, 2019, 12:54 PM
1import os
2import datetime
3import psycopg2
4
5from cs50 import SQL
6from flask import Flask, flash, redirect, render_template, request, session
7from flask_session import Session
8from tempfile import mkdtemp
9from werkzeug.exceptions import default_exceptions
10from werkzeug.security import check_password_hash, generate_password_hash
11from helpers import *
12
13# Configure application
14app = Flask(__name__)
15
16# Ensure templates are auto-reloaded
17app.config["TEMPLATES_AUTO_RELOAD"] = True
18
19# Ensure responses aren't cached
20@app.after_request
21def after_request(response):
22 response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
23 response.headers["Expires"] = 0
24 response.headers["Pragma"] = "no-cache"
25 return response
26
27# Configure session to use filesystem (instead of signed cookies)
28app.config["SESSION_FILE_DIR"] = mkdtemp()
29app.config["SESSION_PERMANENT"] = False
30app.config["SESSION_TYPE"] = "filesystem"
31Session(app)
32
33# Configure CS50 Library to use SQL database
34db = SQL("postgres://njniejknyhtyxb:0efce18ce29dff8371f186ff15d5b5870945be5bb2a743a87ab4f706a6a929b3@ec2-54-246-92-116.eu-west-1.compute.amazonaws.com:5432/dd4jcgtmu8vngd")
35
36@app.route("/")
37@login_required
38def index():
39 """Show a menu of all exercises"""
40 return render_template("index.html")
41
42@app.route("/bench", methods=["GET", "POST"])
43@login_required
44def bench():
45 """Show history of lifts"""
46
47 exercise = "bench"
48 exercise_goal = exercise + "_goal"
49
50 # Check if the user has made any entries in the sets table
51 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session["user_id"])
52
53 # Getting the current max rep and the goal
54 current = result[0]["bench"]
55 goal = result[0]["bench_goal"]
56 remaining = goal - current
57 if request.method == "POST":
58 if current == 0:
59 # Inserting first set
60 insert_set(exercise, 1, 1, request.form.get("benchORM"))
61
62 # Updating the current bench for the first time
63 update_maxrep(exercise, request.form.get("benchORM"))
64
65 # Updating the goal for the first time
66 update_maxrep(exercise_goal, request.form.get("goal"))
67
68 bench = float(request.form.get("benchORM"))
69 goal = float(request.form.get("goal"))
70
71 return render_template("bench.html", bench = bench, goal = goal, remaining = goal - bench, history = history_of_exercise(exercise))
72 else:
73 # Recording a new lift
74 insert_set(exercise, request.form.get("sets"), request.form.get("reps"), request.form.get("weight"))
75 new_record = float(request.form.get("weight"))
76 if new_record > current:
77 if new_record >= goal:
78 update_maxrep(exercise_goal, new_record + 5)
79 update_maxrep(exercise, new_record)
80 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session['user_id'])
81 current = result[0]["bench"]
82 goal = result[0]["bench_goal"]
83 remaining = goal - current
84 return render_template("bench.html", bench = current, goal = goal, remaining = remaining, history = history_of_exercise(exercise))
85 else:
86 return check_and_render("bench", current, goal, history_of_exercise(exercise))
87
88@app.route("/squat", methods=["GET", "POST"])
89@login_required
90def squat():
91 """Show history of squats"""
92
93 exercise = "squat"
94 exercise_goal = exercise + "_goal"
95
96 # Check if the user has made any entries in the sets table
97 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session["user_id"])
98
99 # Getting the current max rep and the goal
100 current = result[0]["squat"]
101 goal = result[0]["squat_goal"]
102 remaining = goal - current
103 if request.method == "POST":
104 if current == 0:
105 # Inserting first set
106 insert_set(exercise, 1, 1, request.form.get("squatORM"))
107
108 # Updating the current squat for the first time
109 update_maxrep(exercise, request.form.get("squatORM"))
110
111 # Updating the goal for the first time
112 update_maxrep(exercise_goal, request.form.get("goal"))
113
114 squat = float(request.form.get("squatORM"))
115 goal = float(request.form.get("goal"))
116
117 return render_template("squat.html", squat = squat, goal = goal, remaining = goal - squat, history = history_of_exercise(exercise))
118 else:
119 # Recording a new lift
120 insert_set(exercise, request.form.get("sets"), request.form.get("reps"), request.form.get("weight"))
121 new_record = float(request.form.get("weight"))
122 if new_record > current:
123 if new_record >= goal:
124 update_maxrep(exercise_goal, new_record + 5)
125 update_maxrep(exercise, new_record)
126 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session['user_id'])
127 current = result[0]["squat"]
128 goal = result[0]["squat_goal"]
129 remaining = goal - current
130 return render_template("squat.html", squat = current, goal = goal, remaining = remaining, history = history_of_exercise(exercise))
131 else:
132 return check_and_render("squat", current, goal, history_of_exercise(exercise))
133
134@app.route("/deadlift", methods=["GET", "POST"])
135@login_required
136def deadlift():
137 """Show history of deadlifts"""
138
139 exercise = "deadlift"
140 exercise_goal = exercise + "_goal"
141
142 # Check if the user has made any entries in the sets table
143 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session["user_id"])
144
145 # Getting the current max rep and the goal
146 current = result[0]["deadlift"]
147 goal = result[0]["deadlift_goal"]
148 remaining = goal - current
149 if request.method == "POST":
150 if current == 0:
151 # Inserting first set
152 insert_set(exercise, 1, 1, request.form.get("deadliftORM"))
153
154 # Updating the current deadlift for the first time
155 update_maxrep(exercise, request.form.get("deadliftORM"))
156
157 # Updating the goal for the first time
158 update_maxrep(exercise_goal, request.form.get("goal"))
159
160 deadlift = float(request.form.get("deadliftORM"))
161 goal = float(request.form.get("goal"))
162
163 return render_template("deadlift.html", deadlift = deadlift, goal = goal, remaining = goal - deadlift, history = history_of_exercise(exercise))
164 else:
165 # Recording a new lift
166 insert_set(exercise, request.form.get("sets"), request.form.get("reps"), request.form.get("weight"))
167 new_record = float(request.form.get("weight"))
168 if new_record > current:
169 if new_record >= goal:
170 update_maxrep(exercise_goal, new_record + 5)
171 update_maxrep(exercise, new_record)
172 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session['user_id'])
173 current = result[0]["deadlift"]
174 goal = result[0]["deadlift_goal"]
175 remaining = goal - current
176 return render_template("deadlift.html", deadlift = current, goal = goal, remaining = remaining, history = history_of_exercise(exercise))
177 else:
178 return check_and_render("deadlift", current, goal, history_of_exercise(exercise))
179
180@app.route("/overheadpress", methods=["GET", "POST"])
181@login_required
182def overheadpress():
183 """Show history of overheadpress"""
184
185 exercise = "overheadpress"
186 exercise_goal = exercise + "_goal"
187
188 # Check if the user has made any entries in the sets table
189 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session["user_id"])
190
191 # Getting the current max rep and the goal
192 current = result[0]["overheadpress"]
193 goal = result[0]["overheadpress_goal"]
194 remaining = goal - current
195 if request.method == "POST":
196 if current == 0:
197 # Inserting first set
198 insert_set(exercise, 1, 1, request.form.get("overheadpressORM"))
199
200 # Updating the current overheadpress for the first time
201 update_maxrep(exercise, request.form.get("overheadpressORM"))
202
203 # Updating the goal for the first time
204 update_maxrep(exercise_goal, request.form.get("goal"))
205
206 overheadpress = float(request.form.get("overheadpressORM"))
207 goal = float(request.form.get("goal"))
208
209 return render_template("overheadpress.html", overheadpress = overheadpress, goal = goal, remaining = goal - overheadpress, history = history_of_exercise(exercise))
210 else:
211 # Recording a new lift
212 insert_set(exercise, request.form.get("sets"), request.form.get("reps"), request.form.get("weight"))
213 new_record = float(request.form.get("weight"))
214 if new_record > current:
215 if new_record >= goal:
216 update_maxrep(exercise_goal, new_record + 5)
217 update_maxrep(exercise, new_record)
218 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session['user_id'])
219 current = result[0]["overheadpress"]
220 goal = result[0]["overheadpress_goal"]
221 remaining = goal - current
222 return render_template("overheadpress.html", overheadpress = current, goal = goal, remaining = remaining, history = history_of_exercise(exercise))
223 else:
224 return check_and_render("overheadpress", current, goal, history_of_exercise(exercise))
225
226@app.route("/pullups", methods=["GET", "POST"])
227@login_required
228def pullups():
229 """Show history of pullups"""
230
231 exercise = "pullups"
232 exercise_goal = exercise + "_goal"
233
234 # Check if the user has made any entries in the sets table
235 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session["user_id"])
236
237 # Getting the current max rep and the goal
238 current = result[0]["pullups"]
239 goal = result[0]["pullups_goal"]
240 remaining = goal - current
241 if request.method == "POST":
242 if current == 0:
243 # Inserting first set
244 insert_set(exercise, 1, request.form.get("pullupsORM"), 0)
245
246 # Updating the current pullups for the first time
247 update_maxrep(exercise, request.form.get("pullupsORM"))
248
249 # Updating the goal for the first time
250 update_maxrep(exercise_goal, request.form.get("goal"))
251
252 pullups = int(request.form.get("pullupsORM"))
253 goal = int(request.form.get("goal"))
254
255 return render_template("pullups.html", pullups = pullups, goal = goal, remaining = goal - pullups, history = history_of_exercise(exercise))
256 else:
257 # Recording a new lift
258 insert_set(exercise, request.form.get("sets"), request.form.get("reps"), 0)
259 new_record = int(request.form.get("reps"))
260 if new_record > current:
261 if new_record >= goal:
262 update_maxrep(exercise_goal, new_record + 5)
263 update_maxrep(exercise, new_record)
264 result = db.execute("SELECT * FROM maxrep WHERE user_id = :user_id", user_id = session['user_id'])
265 current = result[0]["pullups"]
266 goal = result[0]["pullups_goal"]
267 remaining = int(goal) - int(current)
268 return render_template("pullups.html", pullups = current, goal = goal, remaining = remaining, history = history_of_exercise(exercise))
269 else:
270 return check_and_render("pullups", current, goal, history_of_exercise(exercise))
271
272@app.route("/nutrition", methods=["GET", "POST"])
273@login_required
274def nutrition():
275 caloriesGoal = db.execute("SELECT calories FROM calories WHERE user_id = :user_id", user_id = session["user_id"])
276 if caloriesGoal[0]["calories"] == 0:
277 return render_template("nutrition.html", caloriesGoal = caloriesGoal[0], dailyCalories = 0)
278 if request.method == "POST":
279 calorieIntake = request.form.get("calorieIntake")
280 food = request.form.get("food")
281 checkDate = select_from_calorieintake("user_id")
282 if not checkDate:
283 db.execute("INSERT INTO calorieintake (user_id, food, calories, date) VALUES (:user_id, :food, :calorieIntake, :date)",
284 user_id = session["user_id"],
285 food = food,
286 calorieIntake = calorieIntake,
287 date = datetime.date.today())
288 else:
289 calories = select_from_calorieintake("calories")
290 recordedFood = select_from_calorieintake("food")
291 db.execute ("""UPDATE calorieintake SET calories=:calories WHERE user_id = :user_id AND date = :date""",
292 calories = calories[0]['calories'] + int(calorieIntake),
293 user_id = session['user_id'],
294 date = datetime.date.today())
295 db.execute ("""UPDATE calorieintake SET food=:food WHERE user_id = :user_id AND date = :date""",
296 food = recordedFood[0]['food'] + food,
297 user_id = session['user_id'],
298 date = datetime.date.today())
299
300 return render_template("nutrition.html", caloriesGoal = caloriesGoal[0], dailyCalories = calories[0]["calories"] + int(calorieIntake))
301 else:
302 calories = select_from_calorieintake("calories")
303 if not calories:
304 return render_template("nutrition.html", caloriesGoal = caloriesGoal[0], dailyCalories = 0)
305 return render_template("nutrition.html", caloriesGoal = caloriesGoal[0], dailyCalories = calories[0]["calories"])
306
307@app.route("/login", methods=["GET", "POST"])
308def login():
309 """Log user in"""
310
311 # Forget any user_id
312 session.clear()
313
314 # User reached route via POST (as by submitting a form via POST)
315 if request.method == "POST":
316
317 # Query database for username
318 rows = db.execute("SELECT * FROM users WHERE username = :username",
319 username=request.form.get("username"))
320
321 # Ensure username exists and password is correct
322 if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
323 return render_template("loginInvalid.html")
324
325 # Remember which user has logged in
326 session["user_id"] = rows[0]["id"]
327
328 # Redirect user to home page
329 return redirect("/")
330
331 # User reached route via GET (as by clicking a link or via redirect)
332 else:
333 return render_template("login.html")
334
335
336@app.route("/logout")
337def logout():
338 """Log user out"""
339
340 # Forget any user_id
341 session.clear()
342
343 # Redirect user to login form
344 return redirect("/")
345
346@app.route("/goals", methods=["GET", "POST"])
347@login_required
348def goals():
349 """Show the current goals of the user"""
350 goals = db.execute("SELECT bench_goal, squat_goal, deadlift_goal, overheadpress_goal, pullups_goal FROM maxrep WHERE user_id = :user_id", user_id = session["user_id"])
351 return render_template("goals.html", goals = goals)
352
353@app.route("/stats", methods=["GET", "POST"])
354@login_required
355def stats():
356 """Show the current stats of the user."""
357 stats = db.execute("SELECT bench, squat, deadlift, overheadpress, pullups FROM maxrep WHERE user_id = :user_id", user_id = session["user_id"])
358 return render_template("stats.html", stats = stats)
359
360@app.route("/history", methods=["GET", "POST"])
361@login_required
362def history():
363 """Show history of all lifts"""
364 history = db.execute("SELECT exercise, sets, reps, kg, date FROM sets WHERE user_id = :user_id", user_id = session["user_id"])
365 return render_template("history.html", history = history)
366
367@app.route("/profile", methods=["GET", "POST"])
368@login_required
369def profile():
370 """Profile page of the user"""
371 username = db.execute("SELECT username FROM users WHERE id = :user_id", user_id = session["user_id"])
372 posts = db.execute("SELECT post, id FROM posts WHERE user_id = :user_id", user_id = session["user_id"])
373
374 # Reverse the posts so that the newest are on top
375 posts.reverse()
376 if request.method == "POST":
377 post = request.form.get("post")
378
379 # If there is no post, the delete button must be pressed
380 if not post:
381 return delete_post(username)
382
383 # If there is post, insert it
384 return insert_post(username, post)
385 else:
386 return render_template("profile.html", username = username[0]["username"], posts = posts)
387
388@app.route("/newpass", methods=["GET", "POST"])
389@login_required
390def newpass():
391 """Changes the user's password"""
392 if request.method == "POST":
393 rows = db.execute("SELECT * FROM users WHERE id = :user_id",
394 user_id = session["user_id"])
395
396 # Ensure password is correct, if not render the error template
397 if not check_password_hash(rows[0]["hash"], request.form.get("password")):
398 return render_template("newpassInvalid.html")
399 else:
400 # If it is hash the new pass and update the old value
401 hash = generate_password_hash(request.form.get("newpassword"))
402 update = db.execute("UPDATE users SET hash=:value WHERE id = :user_id",
403 value = hash,
404 user_id = session['user_id'])
405 return index()
406 else:
407 return render_template("newpass.html")
408
409@app.route("/register", methods=["GET", "POST"])
410def register():
411 if request.method == "POST":
412
413 # Hashing the password from the form
414 hash = generate_password_hash(request.form.get("password"))
415
416 # Username and hash as placeholders to protect from injection attacks
417 result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)",
418 username = request.form.get("username"), hash = hash)
419 print(result)
420
421 # If the username is taken render the new template
422 if not result:
423 return render_template("registerAlreadyExists.html")
424
425 rows = db.execute("SELECT * FROM users WHERE username = :username",
426 username=request.form.get("username"))
427
428 # Remember which user has logged in
429 session["user_id"] = rows[0]["id"]
430
431 # When a new user is registered create a new entry in the db for their lifts
432 db.execute("""INSERT INTO maxrep (user_id, bench, squat, deadlift, overheadpress, pullups,
433 bench_goal, squat_goal, deadlift_goal, overheadpress_goal, pullups_goal)
434 VALUES (:user_id, :bench, :squat, :deadlift, :overheadpress, :pullups, :bench_goal, :squat_goal, :deadlift_goal,
435 :overheadpress_goal, :pullups_goal)""",
436 user_id = session['user_id'],
437 bench = 0, squat = 0, deadlift = 0, overheadpress = 0, pullups = 0,
438 bench_goal = 0, squat_goal = 0, deadlift_goal = 0, overheadpress_goal = 0, pullups_goal = 0)
439
440 # Also create an entry in the db for their calories
441 db.execute("""INSERT INTO calories (user_id, calories) VALUES (:user_id, :calories)""",
442 user_id = session['user_id'],
443 calories = 0)
444
445 # Redirect user to home page
446 return index()
447
448 else:
449 return render_template("register.html")
450
451@app.route("/calories", methods=["GET", "POST"])
452@login_required
453def calories():
454 if request.method == "POST":
455 caloriesGoal = request.form.get("caloriesGoal")
456 db.execute ("""UPDATE calories SET calories=:calories WHERE user_id = :user_id""",
457 calories = caloriesGoal,
458 user_id = session['user_id'])
459 return render_template("calories.html")
460 else:
461 return render_template("calories.html")
462
463def errorhandler(e):
464 """Handle error"""
465 return apology(e.name, e.code)
466
467
468# listen for errors
469for code in default_exceptions:
470 app.errorhandler(code)(errorhandler)