-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
380 lines (311 loc) · 11.6 KB
/
app.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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
from flask import (
Flask,
render_template,
redirect,
jsonify,
session,
request,
flash)
from flask_wtf.csrf import CSRFProtect
from flask_debugtoolbar import DebugToolbarExtension
from models import (
connect_db,
db,
User,
Workout,
Exercise,
WorkoutExercise,
Result)
from forms import UserAddForm, LoginForm, SearchExerciseForm, AddWorkoutForm
import os
import queries
uri = os.environ.get("DATABASE_URL", "postgresql:///WODatHome_db")
if uri.startswith("postgres://"):
uri = uri.replace("postgres://", "postgresql://", 1)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = False
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", "SECRET WORKOUT!!!")
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
debug = DebugToolbarExtension(app)
csrf = CSRFProtect(app)
connect_db(app)
@app.route('/')
def root():
if "username" not in session:
return redirect('/home')
else:
username = session['username']
return redirect(f'/users/{username}')
@app.route('/home')
def home_page():
if "username" in session:
return redirect('/')
else:
return render_template('home.html')
@app.route('/register', methods=["GET", "POST"])
def register_user():
if "username" in session:
return redirect('/')
form = UserAddForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
new_user = User.register(username, password)
db.session.commit()
session['username'] = new_user.username
flash("New Account Created.", "success")
return redirect(f'/users/{new_user.username}')
return render_template("register.html", form=form)
@app.route('/login', methods=["GET", "POST"])
def login():
if "username" in session:
return redirect('/')
form = LoginForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
user = User.authenticate(username, password)
if user:
session['username'] = username
return redirect(f'/users/{username}')
flash("Username/Password not found.", "danger")
return render_template('login.html', form=form)
@app.route('/browse', methods=["GET"])
def browse():
form = SearchExerciseForm(request.args)
name_input = request.args.get("name")
category_input = request.args.get("category")
equipment_id_input = request.args.getlist("equipment")
if category_input:
equip_list = queries.get_equip_list(equipment_id_input)
exercises = queries.get_exercises(
equip_list,
name_input,
category_input)
return render_template(
'browse.html',
form=form,
exercises=exercises,
equip_list=equip_list)
return render_template('browse.html', form=form)
@app.route('/exercise/<int:id>')
def exercise_details(id):
e = Exercise.query.get(id)
e_img = queries.get_exercise_image(id)
return render_template('exercise_details.html', e=e, e_img=e_img)
@app.route('/users/<username>')
def user_home(username):
if 'username' not in session or username != session['username']:
flash("You are not authorized to accessed this page.", "danger")
return redirect('/')
else:
user = User.query.filter_by(username=username).one()
workouts = Workout.query.filter_by(user_id=user.id).all()
return render_template('user_home.html', user=user, workouts=workouts)
@app.route('/users/<username>/workout/create', methods=["GET", "POST"])
def create_workout(username):
"""Begin creation of new workout."""
if 'username' not in session or username != session['username']:
flash("You are not authorized to accessed this page.", "danger")
return redirect('/')
else:
user = User.query.filter_by(username=username).one()
form = AddWorkoutForm()
if form.validate_on_submit():
type = form.type.data
name = form.name.data
return redirect(
f'/users/{username}/workout/create/{type}/{name}')
return render_template("create_workout.html", form=form, user=user)
@app.route(
'/users/<username>/workout/create/<workout_type>/<workout_name>',
methods=["GET"])
def set_workout_details(username, workout_type, workout_name):
"""Customize workout details and add exercises"""
if 'username' not in session or username != session['username']:
flash("You are not authorized to accessed this page.", "danger")
return redirect('/')
else:
browse_form = SearchExerciseForm(request.args)
name_input = request.args.get("name")
category_input = request.args.get("category")
equipment_id_input = request.args.getlist("equipment")
if (workout_type == 'AMRAP'):
template = 'add_amrap_exercises.html'
elif (workout_type == 'EMOM'):
template = 'add_emom_exercises.html'
elif (workout_type == 'RFT'):
template = 'add_rft_exercises.html'
if category_input:
equip_list = queries.get_equip_list(equipment_id_input)
exercises = queries.get_exercises(
equip_list,
name_input,
category_input)
return render_template(
template,
browse_form=browse_form,
exercises=exercises,
equip_list=equip_list,
username=username,
workout_name=workout_name)
return render_template(
template,
username=username,
workout_name=workout_name,
browse_form=browse_form)
@app.route('/users/<username>/workout/<int:id>')
def workout_details(username, id):
"""Show the exercises within this workout and give
options to delete and execute workout"""
if 'username' not in session or username != session['username']:
flash("You are not authorized to accessed this page.", "danger")
return redirect('/')
else:
workout = Workout.query.get(id)
exercises = WorkoutExercise.query.filter_by(
workout_id=workout.id
).order_by(WorkoutExercise.order).all()
if workout.type == 'AMRAP':
exercises_per_stage = int(
(len(exercises) - workout.stages + 1) / workout.stages)
workout_stages = []
tick = 0
while tick < len(exercises):
workout_stages.append(exercises[tick:tick+exercises_per_stage])
tick = tick + exercises_per_stage + 1
rest_time = exercises[exercises_per_stage].count
return render_template(
'workout_details.html',
workout=workout,
exercises=exercises,
username=username,
workout_stages=workout_stages,
rest_time=rest_time)
if workout.type == 'EMOM' or workout.type == 'RFT':
return render_template(
'workout_details.html',
username=username,
workout=workout,
exercises=exercises,)
@app.route('/users/<username>/workout/<int:id>/execute')
def execute_workout(username, id):
if 'username' not in session or username != session['username']:
flash("You are not authorized to accessed this page.", "danger")
return redirect('/')
else:
workout = Workout.query.get(id)
exercises = WorkoutExercise.query.filter_by(
workout_id=id).order_by(WorkoutExercise.order).all()
if (workout.type == 'AMRAP'):
template = 'execute_amrap.html'
elif (workout.type == 'EMOM'):
template = 'execute_emom.html'
elif (workout.type == 'RFT'):
template = 'execute_rft.html'
return render_template(
template,
username=username,
workout=workout,
exercises=exercises)
@app.route('/users/<username>/workout/<int:id>/log', methods=["POST"])
def log_results(username, id):
if 'username' not in session or username != session['username']:
flash("You are not authorized to accessed this page.", "danger")
return redirect('/')
else:
user = User.query.filter_by(username=username).one()
result_notes = request.form.get("results-log")
new_result = Result(
workout_id=id,
user_id=user.id,
note=result_notes)
db.session.add(new_result)
db.session.commit()
return redirect(f'/users/{username}/history')
@app.route('/users/<username>/history')
def workout_history(username):
if 'username' not in session or username != session['username']:
return redirect('/')
else:
user = User.query.filter_by(username=username).one()
results = user.results
return render_template(
'history.html',
username=username,
results=results)
@app.route('/users/<username>/workout/<int:id>/delete', methods=["POST"])
def delete_workout(username, id):
if 'username' not in session or username != session['username']:
flash("You are not authorized to accessed this page.", "danger")
return redirect('/')
else:
workout = Workout.query.get(id)
db.session.delete(workout)
db.session.commit()
return redirect(f'/users/{username}')
@app.route('/logout')
def logout():
session.pop('username')
return redirect('/')
"""For AJAX requests"""
@app.route('/api/workout/<int:id>')
def get_workout(id):
workout = Workout.query.get_or_404(id)
return jsonify(workout.serialize())
@app.route('/api/workout_exercises/<int:id>')
def get_workout_exercises(id):
workout = Workout.query.get_or_404(id)
exercises = WorkoutExercise.query.filter_by(
workout_id=workout.id
).order_by(WorkoutExercise.order).all()
serialized_exercises = []
for exercise in exercises:
exc = {
"name": exercise.exercise.name,
"count": exercise.count,
"count_type": exercise.count_type
}
serialized_exercises.append(exc)
return jsonify(serialized_exercises)
@app.route('/api/workouts', methods=["POST"])
def add_workout():
username = request.json.get("username")
type = request.json.get("type")
name = request.json.get("name")
stages = int(request.json.get("stages"))
stage_time = int(request.json.get("stage_time"))
user = User.query.filter_by(username=username).one()
user_id = user.id
new_workout = Workout(
user_id=user_id,
type=type,
name=name,
stages=stages,
stage_time=stage_time)
db.session.add(new_workout)
db.session.commit()
return ("Workout Created", 201)
@app.route('/api/workout-exercises', methods=["POST"])
def add_workout_exercises():
workout_name = request.json.get("name")
order = request.json.get("order")
exercise_id = request.json.get("exercise_id")
count = request.json.get("count")
count_type = request.json.get("count_type")
workout = Workout.query.filter_by(
name=workout_name
).order_by(
Workout.id.desc()
).first()
new_workout_exercise = WorkoutExercise(
workout_id=workout.id,
order=order,
exercise_id=exercise_id,
count=count,
count_type=count_type)
db.session.add(new_workout_exercise)
db.session.commit()
return ("Workout Exercise Added", 201)