-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
913 lines (694 loc) · 31.1 KB
/
Copy pathapp.py
File metadata and controls
913 lines (694 loc) · 31.1 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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# ########################################
# ########## SETUP
# This file contains all of the route handlers for our Flask application. Most of the routes were adapted from the starter code examples in the exploration unless otherwise noted above each definition.
# The setup was also adapted from the starter code.
from flask import Flask, render_template, request, redirect
import database.db_connector as db
PORT = 8089
app = Flask(__name__)
# ########################################
# ########## ROUTE HANDLERS
# READ ROUTES adapted from build app.py starter.
@app.route("/", methods=["GET"])
def home():
try:
return render_template("home.j2")
except Exception as e:
print(f"Error rendering page: {e}")
return "An error occurred while rendering the page.", 500
# -----------------------------------------------------------------------------------------
# Reset Route - Implemented with the PL wrapper and adapted from the example in class.
# -----------------------------------------------------------------------------------------
@app.route("/reset-db", methods=["POST"])
def reset_database():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
# Call reset procedure
cursor.execute("CALL sp_load_front_range_data();")
while cursor.nextset():
pass
dbConnection.commit()
print("Database reset successful!")
return redirect("/skiers") # Redirect back to see the fresh data
except Exception as e:
print(f"Error resetting database: {e}")
return "An error occurred during database reset.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# ---------------------------------------------------------------------------------------------------------
# Skiers CRUD routes
# ---------------------------------------------------------------------------------------------------------
# #####################################################################
# READ for Skiers adapted from build app.py starter.
# #####################################################################
@app.route("/skiers", methods=["GET"])
def skiers():
try:
dbConnection = db.connectDB() # Open our database connection
# Create and execute our queries
query1 = "SELECT * FROM Skiers;"
skiers = db.query(dbConnection, query1).fetchall()
# Render the skiers.j2 file, and also send the renderer
# a couple objects that contains skiers information
return render_template(
"skiers.j2", skiers=skiers
)
except Exception as e:
print(f"Error executing queries: {e}")
return "An error occurred while executing the database queries.", 500
finally:
# Close the DB connection, if it exists
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# CREATE for Skiers adapted from build app.py starter with our own queries and form data.
# gemini helped us with slicing our name to enforce Varchar(45)
# #####################################################################
@app.route("/skiers/create", methods=["POST"])
def create_skiers():
try:
dbConnection = db.connectDB() # this opens skiers db connection
cursor = dbConnection.cursor()
# Get form data.
Name = request.form["create_skier_name"][:45] # this is a way to enforce the varchar(45) limit on the input. it will raise an error if the input exceeds 45 characters.
Address = request.form["create_skier_address"]
try:
Phone = int(request.form["create_skier_phone"])
except ValueError:
Phone = "9999999999" # default value if input is not a valid integer
Email = request.form["create_skier_email"][:255] # enforce varchar(255) limit on email input
Ability = request.form["create_skier_ability"]
# call create skier sp method. use parameterized queries to prevent injuection attacks like drop table or db.
query1 = "CALL sp_CreateSkier(%s, %s, %s, %s, %s, @s_new_id);"
cursor.execute(query1, (Name, Address, Phone, Email, Ability))
cursor.nextset()
# store the generated skier id for the last inserted row
cursor.execute("SELECT @new_id;")
new_id = cursor.fetchone()[0]
dbConnection.commit() #commit transaction
print(f"""Create skiers.
ID: {new_id}
Name: {Name}
Address {Address}
Phone {Phone}
Email {Email}
Ability {Ability}
""")
# Redirect to the updated webpage by add the path /skiers
return redirect("/skiers")
except Exception as e:
print(f"Error executing queries: {e}")
return ("An error occurred while executing skiers/create this database queries. ", 500,) # ProgError, OpsError, DBError? can be more specific
finally:
# Close the DB Conneciton, if it exists:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# UPDATE for Skiers adapted from starter and applied some parameters
# #####################################################################
@app.route('/skiers/update', methods=['POST'])
def update_skier():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
s_id = request.form['update_skier_id']
s_name = request.form['update_skier_name'] [:45] # enforce varchar(45) limit on name input
s_address = request.form['update_skier_address']
try:
s_phone = int(request.form['update_skier_phone'])
except ValueError:
s_phone = "9999999999" # default value if input is not a valid integer
s_email = request.form['update_skier_email'][:255] # enforce varchar(255) limit on email input
s_ability = request.form['update_skier_ability']
query = "CALL sp_UpdateSkier(%s, %s, %s, %s, %s, %s);"
params = (s_id, s_name, s_address, s_phone, s_email, s_ability)
cursor.execute(query, params)
dbConnection.commit()
print(f"UPDATE skier successful. ID: {s_id}")
return redirect("/skiers")
except Exception as e:
print(f"Error updating skier: {e}")
return "An error occurred while updating the skier.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# DELETE for Skiers adapted from build app.py starter with our own queries and form data.
# #####################################################################
@app.route("/skiers/delete", methods=["POST"])
def delete_skiers():
try:
dbConnection = db.connectDB() # Open our database connection
cursor = dbConnection.cursor()
# Get form data
skier_id = request.form["delete_skier_id"]
# Create and execute our queries
query1 = "CALL sp_DeleteSkier(%s);"
cursor.execute(query1, (skier_id,))
dbConnection.commit() # commit the transaction
print(f"DELETE skiers. ID: {skier_id}")
# Redirect the user to the updated webpage
return redirect("/skiers")
except Exception as e:
print(f"Error executing queries: {e}")
return (
"An error occurred while executing the database queries.",
500,
)
finally:
# Close the DB connection, if it exists
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# ---------------------------------------------------------------------------------------------------------
# Lifts CRUD routes
# ---------------------------------------------------------------------------------------------------------
# #####################################################################
# READ for Lifts adapted from build app.py starter.
# #####################################################################
@app.route("/lifts", methods=["GET"])
def lifts():
try:
dbConnection = db.connectDB() # Open our database connection
# Create and execute our queries
query1 = "SELECT * FROM Lifts;"
lifts = db.query(dbConnection, query1).fetchall()
# render
return render_template(
"lifts.j2", lifts=lifts
)
except Exception as e:
print(f"Error executing queries: {e}")
return "An error occurred while executing the database queries.", 500
finally:
# Close the DB connection, if it exists
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# DELETE for Lifts adapted from starter.
# #####################################################################
@app.route("/lifts/delete", methods=["POST"])
def delete_lifts():
try:
dbConnection = db.connectDB() # Open our database connection
cursor = dbConnection.cursor()
# Get form data
lift_id = request.form["delete_lift_id"]
# Create and execute our queries
query1 = "CALL sp_DeleteLifts(%s);"
cursor.execute(query1, (lift_id,))
dbConnection.commit() # commit the transaction
print(f"DELETE lifts. ID: {lift_id}")
# Redirect the user to the updated webpage
return redirect("/lifts")
except Exception as e:
print(f"Error executing queries: {e}")
return (
"An error occurred while executing the database queries.",
500,
)
finally:
# Close the DB connection, if it exists
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# UPDATE for Lifts adapted from starter.
# #####################################################################
@app.route('/lifts/update', methods=['POST'])
def update_lifts():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
l_id = request.form['update_lift_id']
l_status = request.form['update_lift_status']
query = "CALL sp_UpdateLifts(%s, %s);"
params = (l_id, l_status)
cursor.execute(query, params)
dbConnection.commit()
print(f"UPDATE lifts successful. ID: {l_id}")
return redirect("/lifts")
except Exception as e:
print(f"Error updating lifts: {e}")
return "An error occurred while updating the lifts.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# --------------------------------------------------------------------------------------------------
# SkiersLifts CRD adapted from build app.py starter with our own queries and form data.
# no need for update
# -------------------------------------------------------------------------------------------------
# #####################################################################
# READ for SkiersLifts adapted from starter with our own queries.
# #####################################################################
@app.route("/skierslifts", methods=["GET"])
def skierslifts():
try:
dbConnection = db.connectDB() # Open our database connection
query1 = """
SELECT
SkiersLifts.SkiersLiftsID,
Skiers.Name AS SkierName,
Lifts.LiftName AS LiftName
FROM SkiersLifts
INNER JOIN Skiers ON SkiersLifts.Skiers_SkierID = Skiers.SkierID
INNER JOIN Lifts ON SkiersLifts.Lifts_LiftID = Lifts.LiftID;
"""
skierslifts = db.query(dbConnection, query1).fetchall()
query2 = "SELECT SkierID, Name FROM Skiers;"
skiers = db.query(dbConnection, query2).fetchall()
query3 = "SELECT LiftID, LiftName FROM Lifts;"
lifts = db.query(dbConnection, query3).fetchall()
return render_template(
"skierslifts.j2", skierslifts=skierslifts, skiers=skiers, lifts=lifts
)
except Exception as e:
print(f"Error executing queries: {e}")
return "An error occurred while executing the database queries.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# CREATE for SkiersLifts adapted from starter with our own queries and form data.
# #####################################################################
@app.route("/skierslifts/create", methods=["POST"])
def create_skierslifts():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
Skiers_SkierID = int(request.form["create_skier_skierId"])
Lifts_LiftID = int(request.form["create_lift_liftId"])
cursor.execute(
"CALL sp_CreateSkiersLifts(%s,%s,@new_id);",
(Skiers_SkierID, Lifts_LiftID)
)
cursor.nextset()
cursor.execute("SELECT @new_id;")
new_id = cursor.fetchone()[0]
dbConnection.commit()
return redirect("/skierslifts")
except Exception as e:
print("REAL ERROR:", e)
return ("Create skierslifts failed", 500)
finally:
if "dbConnection" in locals():
dbConnection.close()
# #####################################################################
# DELETE for SkiersLifts adapted from starter with our own queries and form data.
# #####################################################################
@app.route("/skierslifts/delete", methods=["POST"])
def delete_skierslifts():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
skierslifts_id = request.form["delete_skierslifts_id"]
query1 = "CALL sp_DeleteSkiersLifts(%s);"
cursor.execute(query1, (skierslifts_id,))
dbConnection.commit()
print(f"DELETE skierslifts. ID: {skierslifts_id}")
return redirect("/skierslifts")
except Exception as e:
print(f"Error executing queries: {e}")
return (
"An error occurred while executing the database queries.",
500,
)
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# --------------------------------------------------------------------------------------------------
# Passes CRD
# only need Create, Read, and Delete
# --------------------------------------------------------------------------------------------------
# #####################################################################
# READ for Passes adapted from build app.py starter with our own queries.
# #####################################################################
@app.route("/passes", methods=["GET"])
def passes():
try:
dbConnection = db.connectDB()
passes_query = """SELECT
PassID,
Type,
DATE(PurchaseDate) AS PurchaseDate,
DATE(ExpirationDate) AS ExpirationDate,
Skiers_SkierID,
Skiers.Name AS SkierName
FROM Passes
INNER JOIN Skiers ON Passes.Skiers_SkierID = Skiers.SkierID;
"""
passes = db.query(dbConnection, passes_query).fetchall()
skiers_query = "SELECT SkierID, Name FROM Skiers;"
skiers = db.query(dbConnection, skiers_query).fetchall()
return render_template(
"passes.j2",
passes=passes,
skiers=skiers
)
finally:
if "dbConnection" in locals():
dbConnection.close()
# #####################################################################
# CREATE for Passes adapted from starter. Gemini helped us with queries so that we could remove expiration input.
# #####################################################################
@app.route("/passes/create", methods=["POST"])
def create_passes():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
p_type = request.form["create_pass_type"]
p_purchase_date = request.form["create_purchase_date"].replace("T"," ") + ":00"
skier_id = int(request.form["create_skier_skierId"])
cursor.execute(
"CALL sp_CreatePass(%s, %s, %s, @new_id);",
(p_type, p_purchase_date, skier_id)
)
cursor.execute("SELECT @new_id;")
new_id = cursor.fetchone()[0]
dbConnection.commit()
return redirect("/passes")
except Exception as e:
print("DB ERROR:", e)
return ("Create pass failed", 500)
finally:
if "dbConnection" in locals():
dbConnection.close()
# #####################################################################
# DELETE for Passes adapted from starter.
# #####################################################################
@app.route("/passes/delete", methods=["POST"])
def delete_passes():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
pass_id = request.form["delete_pass_id"]
query1 = "CALL sp_DeletePass(%s);"
cursor.execute(query1, (pass_id,))
dbConnection.commit()
print(f"DELETE pass. ID: {pass_id} Name: {pass_id}")
return redirect("/passes")
except Exception as e:
print(f"Error executing queries: {e}")
return (
"An error occurred while executing the database queries.",
500,
)
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# --------------------------------------------------------------------------------------------------
# RentalInventory CRD
# only need Create, Read, and Delete
# -------------------------------------------------------------------------------------------------
# #####################################################################
# READ for RentalInventory adapted from build app.py starter with our own queries.
# #####################################################################
@app.route("/rentalinventory", methods=["GET"])
def rentalinventory():
try:
dbConnection = db.connectDB()
query1 = "SELECT * FROM RentalInventory;"
rentalinventory = db.query(dbConnection, query1).fetchall()
return render_template(
"rentalinventory.j2", rentalinventory=rentalinventory
)
except Exception as e:
print(f"Error executing queries: {e}")
return "An error occurred while executing the database queries.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# CREATE for RentalInventory items adapted from starter with our own queries and form data.
# #####################################################################
@app.route("/rentalinventory/create", methods=["POST"])
def create_rentalinventory():
dbConnection = None
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
Type = request.form["create_rental_type"][:45] # enforce varchar(45) limit on type input
query = "CALL sp_CreateRentalInventory(%s, @new_id);"
cursor.execute(query, (Type,))
cursor.execute("SELECT @new_id;")
row = cursor.fetchone()
new_id = row[0] if row else None
dbConnection.commit()
print(f"Created ID: {new_id}")
return redirect("/rentalinventory")
except Exception as e:
if dbConnection:
dbConnection.rollback()
print(f"Error: {e}")
return "An error occurred during creation.", 500
finally:
if dbConnection:
cursor.close()
dbConnection.close()
# #####################################################################
# Delete for RentalInventory adapted from starter with our own queries and form data.
# #####################################################################
@app.route("/rentalinventory/delete", methods=["POST"])
def delete_rentalinventory():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
rental_id = request.form["delete_rental_id"]
query1 = "CALL sp_DeleteRentalInventory(%s);"
cursor.execute(query1, (rental_id,))
dbConnection.commit()
print(f"DELETE rental inventory item. ID: {rental_id}")
return redirect("/rentalinventory")
except Exception as e:
print(f"Error executing queries: {e}")
return (
"An error occurred while executing the database queries.",
500,
)
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# --------------------------------------------------------------------------------------------------
# SkiersRentals CRUD
# --------------------------------------------------------------------------------------------------
# ########################################################################
# READ for SkiersRentals adapted from build app.py starter with queries that were provided by Gemini
# that helped us with our first iteration of the update button and were functional after implementing the SP.
# #######################################################################
@app.route("/skiersrentals", methods=["GET"])
def skiersrentals():
dbConnection = None
try:
dbConnection = db.connectDB()
query_main = """
SELECT SkiersRentals.SkiersRentalsID, Skiers.Name AS SkierName, RentalInventory.Type AS ItemType
FROM SkiersRentals
JOIN Skiers ON Skiers_SkierID = SkierID
JOIN RentalInventory ON RentalInventory_RentalID = RentalID;
"""
results = db.query(dbConnection, query_main).fetchall()
skiers_list = db.query(dbConnection, "SELECT SkierID, Name FROM Skiers;").fetchall()
items_list = db.query(dbConnection, "SELECT RentalID, Type FROM RentalInventory;").fetchall()
rental_to_update = None
target_id = request.args.get('id')
if target_id:
query_single = "SELECT * FROM SkiersRentals WHERE SkiersRentalsID = %s;"
rental_to_update = db.query(dbConnection, query_single, (target_id,)).fetchone()
return render_template("skiersrentals.j2",
skiersrentals=results,
skiers=skiers_list,
rentals=items_list,
rental=rental_to_update)
finally:
if dbConnection:
dbConnection.close()
# ########################################################################
# CREATE for SkiersRentals adapted from starter.
# ########################################################################
@app.route("/skiersrentals/create", methods=["POST"])
def create_skiersrentals():
dbConnection = None
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
s_id = request.form["create_skier_skierId"]
r_id = request.form["create_rental_rentalId"]
cursor.execute("CALL sp_CreateSkiersRentals(%s, %s, @sr_id);", (s_id, r_id))
cursor.execute("SELECT @sr_id;")
new_sr_id = cursor.fetchone()[0]
print(f"Created SkiersRentals with ID: {new_sr_id}")
dbConnection.commit()
return redirect("/skiersrentals")
except Exception as e:
print(f"CREATE ERROR: {e}")
return "Failed to create rental.", 500
finally:
if dbConnection:
dbConnection.close()
# ########################################################################
# UPDATE for SkiersRentals adapted from starter, improved with gemini suggestions after implementing the appearing button.
# ########################################################################
@app.route("/skiersrentals/update", methods=["POST"])
def update_skiersrentals():
dbConnection = None
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
rental_id = request.form["update_rental_id"]
skier_id = request.form["update_skier_id"]
item_id = request.form["update_item_id"]
cursor.execute(
"CALL sp_UpdateSkiersRentals(%s, %s, %s);",
(rental_id, skier_id, item_id)
)
while cursor.nextset():
pass
dbConnection.commit()
print(f"Successfully updated Rental ID: {rental_id}")
return redirect("/skiersrentals")
except Exception as e:
print(f"UPDATE ERROR: {e}")
return f"Update failed: {e}", 500
finally:
if dbConnection:
dbConnection.close()
# ########################################################################
# DELETE for SkiersRentals adapted from starter with our own queries and form data.
# ########################################################################
@app.route("/skiersrentals/delete", methods=["POST"])
def delete_skiersrentals():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
sr_id = request.form["delete_skiersrentals_id"]
cursor.execute("CALL sp_DeleteSkiersRentals(%s);", (sr_id,))
dbConnection.commit()
print(f"DELETE skiersrentals. ID: {sr_id}")
return redirect("/skiersrentals")
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# --------------------------------------------------------------------------------------------------
# Trails
# --------------------------------------------------------------------------------------------------
# #####################################################################
# Read for Trails adapted from build app.py starter with our own queries.
# #####################################################################
@app.route("/trails", methods=["GET"])
def trails():
try:
dbConnection = db.connectDB() # Open our database connection
query1 = "SELECT * FROM Trails;"
trails = db.query(dbConnection, query1).fetchall()
return render_template(
"trails.j2", trails=trails
)
except Exception as e:
print(f"Error executing queries: {e}")
return "An error occurred while executing the database queries.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# UPDATE for Trails adapted from starter with our own queries and form data.
# #####################################################################
@app.route('/trails/update', methods=['POST'])
def update_trails():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
t_id = request.form['update_trail_id']
t_status = request.form['update_trail_status']
query = "CALL sp_UpdateTrails(%s, %s);"
params = (t_id, t_status)
cursor.execute(query, params)
dbConnection.commit()
print(f"UPDATE trails successful. ID: {t_id}")
return redirect("/trails")
except Exception as e:
print(f"Error updating trails: {e}")
return "An error occurred while updating the trails.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# --------------------------------------------------------------------------------------------------
# Skierstrails CRD
# only need read, update, and delete
# --------------------------------------------------------------------------------------------------
# #####################################################################
# READ for Skierstrails adapted from build app.py starter
# #####################################################################
@app.route("/skierstrails", methods=["GET"])
def skierstrails():
try:
dbConnection = db.connectDB()
query1 = """
SELECT
SkiersTrails.SkiersTrailsID,
Skiers.Name AS SkierName,
Trails.TrailName AS TrailName
FROM SkiersTrails
INNER JOIN Skiers ON SkiersTrails.Skiers_SkierID = Skiers.SkierID
INNER JOIN Trails ON SkiersTrails.Trails_TrailID = Trails.TrailID;
"""
skierstrails = db.query(dbConnection, query1).fetchall()
query2 = "SELECT SkierID, Name FROM Skiers;"
skiers = db.query(dbConnection, query2).fetchall()
query3 = "SELECT TrailID, TrailName FROM Trails;"
trails = db.query(dbConnection, query3).fetchall()
return render_template(
"skierstrails.j2", skierstrails=skierstrails, skiers=skiers, trails=trails
)
except Exception as e:
print(f"Error executing queries: {e}")
return "An error occurred while executing the database queries.", 500
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# CREATE for Skierstrails adapted from starter.
# #####################################################################
@app.route("/skierstrails/create", methods=["POST"])
def create_skierstrails():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
Skiers_SkierID = int(request.form["create_skier_skierId"])
Trails_TrailID = int(request.form["create_trail_trailId"])
cursor.execute(
"CALL sp_CreateSkiersTrails(%s,%s,@new_id);",
(Skiers_SkierID, Trails_TrailID)
)
cursor.nextset()
cursor.execute("SELECT @new_id;")
new_id = cursor.fetchone()[0]
dbConnection.commit()
return redirect("/skierstrails")
except Exception as e:
print("REAL ERROR:", e)
return ("Create skierstrails failed", 500)
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# #####################################################################
# DELETE for Skierstrails adapted from starter with our own queries and form data.
# #####################################################################
@app.route("/skierstrails/delete", methods=["POST"])
def delete_skierstrails():
try:
dbConnection = db.connectDB()
cursor = dbConnection.cursor()
st_id = request.form["delete_skierstrails_id"]
cursor.execute("CALL sp_DeleteSkiersTrails(%s);", (st_id,))
dbConnection.commit()
print(f"DELETE skierstrails. ID: {st_id}")
return redirect("/skierstrails")
finally:
if "dbConnection" in locals() and dbConnection:
dbConnection.close()
# ########################################################################
# ########## LISTENER
if __name__ == "__main__":
app.run(
port=PORT, debug=True
) # debug is an optional parameter. Behaves like nodemon in Node.