-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
808 lines (648 loc) · 27.9 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
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
from flask import Flask, flash
from flask import render_template
from flask import request
from flask import redirect
from flask import url_for
import datetime
import mysql.connector
from mysql.connector import FieldType
import connect
app = Flask(__name__)
app.secret_key = 'super secret key'
dbconn = None
connection = None
def getCursor():
global dbconn
global connection
connection = mysql.connector.connect(user=connect.dbuser, \
password=connect.dbpass, host=connect.dbhost, \
database=connect.dbname, autocommit=True)
dbconn = connection.cursor()
return dbconn
def ageCalculate(sDate):
sY = sDate.split("-")[0]
sM = sDate.split("-")[1]
sD = sDate.split("-")[2]
try:
iD=int(sD)
iM=int(sM)
iY=int(sY)
iDnow=datetime.datetime.now().day
iMnow=datetime.datetime.now().month
iYnow=datetime.datetime.now().year
# check the birthday if it is later than current date
# if iY>datetime.now().year or (iY==datetime.now().year and iM>=datetime.now().month and iD>datetime.now().day):
if iY>iYnow or (iY==iYnow and iM>=iMnow and iD>iDnow):
return 0
else:
today = str(datetime.datetime.now().strftime('%Y-%m-%d')).split("-")
monthday = int(today[1] + today[2])
year = int(today[0])
b_monthday = int(sM + sD)
b_year = iY
if (monthday) >= b_monthday:
age = year - b_year
else:
age = year - b_year - 1
except Exception as ex:
print(ex)
return -1
ageBirthday = {'age': age, 'birthday': sY +"-"+ sM +"-"+ sD}
return ageBirthday
def runsCalculate(runDetail):
# Calculate the Run Totals
# Return a list including the course type, driver id, time, cones hit, WD status and the Run Totals.
# Define the list include Run totals
update_list = []
for listRun in runDetail:
# Calculate WD time
if listRun[11] == 1:
wd_time = 10
elif listRun[11] == 0:
wd_time = 0
elif listRun[11] == None:
wd_time = 0
else:
print("\nerror: Invalid WD data\n")
return -1
# Get time
if listRun[9] == None :
time = 0
elif type(listRun[9]) in (float,int) :
time = listRun[9]
else:
print("\nerror: Invalid Time data\n")
return -1
# Make sure time is recorded to the nearest 0.01 of a second
# time = Decimal(time).quantize(Decimal("0.00"))
time = round(time,2)
# Get num of cones
if listRun[10] == None:
cones_time = 0
elif type(listRun[10]) == int:
cones_time = listRun[10]
else:
print("\nerror: Invalid Cones data\n")
return -1
# Calculate total time (If time is equal to 0, the result is invalid. run Total should also be 0)
if time > 0:
run_total = round((time + cones_time*5 + wd_time),2)
else:
run_total = 0.0
# Put into a list with the course type, driver id, basic time, cones hit, WD status and the Run Totals.
run = (
listRun[0],
listRun[1],
listRun[2],
listRun[3],
listRun[4],
listRun[5],
listRun[6],
listRun[7],
listRun[8],
listRun[9],
listRun[10],
listRun[11],
run_total)
update_list.append(list(run))
return update_list
def overallCalculate(runDetail):
# Calculate the Overall Results and add it into return list
# Sort Run Details list
# Sort rule: first by surname, then by firstname, then by Course ID, then by Run Total.
sort_list = sorted(runDetail, key=lambda x:(x[2],x[1],x[6],x[12]))
# Put all courses results of one driver into one list
temp_list = []
j = 0
while j<len(sort_list):
list = []
for i in range(0, 6):
list.append(sort_list[j][i])
for i in range(1, 13):
list.append(sort_list[j][12])
j=j+1
temp_list.append(list)
# Calculate the overall result
overall_list = []
for list in temp_list:
list2 = []
overallResult = 0.0
for i in range(0, 6):
list2.append(list[i])
# Choose the best of both run results for each course
# Set "dnf" flag to course result which both run results are 0.0
for i in range(6, 18, 2):
if list[i+1] == 0.0:
list2.append("dnf")
overallResult = 999999 # overallResult Value 999999 means NQ
elif list[i] == 0.0:
list2.append(list[i+1])
else:
list2.append(min(list[i],list[i+1]))
# Calculate the overall result
if overallResult != 999999:
for i in range(6, 12):
overallResult = list2[i] + overallResult
overallResult = round(overallResult,2)
list2.append(overallResult)
overall_list.append(list2)
# Sort Overall Results list
# Sort rule: first by Overall Results, then by surname, then by firstname.
overall_list = sorted(overall_list, key=lambda x:(x[12],x[2],x[1]))
# Winner get "cup" flag, the next 4 get "prize" flag
resultsNum = len(overall_list)
if resultsNum > 4:
overall_list[0].append("cup")
for i in range(1, 5):
overall_list[i].append("prize")
elif resultsNum == 1:
overall_list[0].append("cup")
elif resultsNum < 5:
overall_list[0].append("cup")
for i in range(1, resultsNum):
overall_list[i].append("prize")
# Set "NQ" flag to overall result
for i in range(0, resultsNum):
if overall_list[i][12] == 999999:
overall_list[i][12] = "NQ"
return overall_list
@app.route("/")
def home():
return render_template("home.html")
@app.route("/admin")
def admin():
return render_template("admin.html")
@app.route("/adminhome")
def adminhome():
return render_template("adminhome.html")
@app.route("/base")
def base():
return render_template("base.html")
@app.route("/listdrivers")
def listdrivers():
connection = getCursor()
sql = """ SELECT * FROM driver
INNER JOIN car ON driver.car = car.car_num
ORDER BY driver.surname, driver.first_name;"""
connection.execute(sql)
driverList = connection.fetchall()
for list in driverList:
print(list)
return render_template("driverlist.html", driver_list = driverList)
@app.route("/listjuniordrivers")
def listjunior():
connection = getCursor()
sql = """ SELECT d1.driver_id, d1.first_name, d1.surname, d1.age,
car.model, car.drive_class, d2.first_name, d2.surname FROM driver d1
INNER JOIN car ON d1.car = car.car_num
LEFT JOIN driver d2 ON d1.caregiver = d2.driver_id
ORDER BY d1.age DESC, d1.surname;"""
connection.execute(sql)
driverList = connection.fetchall()
for list in driverList:
print(list)
return render_template("juniorlist.html", driver_list = driverList)
@app.route("/listcourses")
def listcourses():
connection = getCursor()
connection.execute("SELECT * FROM course;")
courseList = connection.fetchall()
return render_template("courselist.html", course_list = courseList)
@app.route("/graph")
def showgraph():
connection = getCursor()
sql = """ SELECT driver.driver_id, driver.first_name, driver.surname, driver.age,
car.model, car.drive_class, run.crs_id, course.name,
run.run_num, run.seconds, run.cones, run.wd
FROM driver
INNER JOIN car ON driver.car = car.car_num
INNER JOIN run ON driver.driver_id = run.dr_id
INNER JOIN course ON course.course_id = run.crs_id
ORDER BY run.crs_id;"""
connection.execute(sql)
runDetail = connection.fetchall()
# Calculate the Run Total
runDetailUpdate = runsCalculate(runDetail)
# Calculate the Overall Result
overallResults = overallCalculate(runDetailUpdate)
# Insert code to get top 5 drivers overall, ordered by their final results.
# Use that to construct 2 lists: bestDriverList containing the names, resultsList containing the final result values
# Names should include their ID and a trailing space, eg '133 Oliver Ngatai '
bestDriverList = []
juniorFlag = ""
for i in range(4, -1, -1):
if overallResults[i][3] == None:
juniorFlag = ""
elif overallResults[i][3] <=25:
juniorFlag = " (J)"
bestDriverList.append(" "+str(overallResults[i][0])+" " + overallResults[i][1] + " " + overallResults[i][2] + juniorFlag + " " )
bestResultsList = []
for i in range(4, -1, -1):
bestResultsList.append(overallResults[i][12])
#Debug info
print(bestDriverList)
print(bestResultsList)
return render_template("top5graph.html", name_list = bestDriverList, value_list = bestResultsList)
@app.route("/rundetail", methods=['POST','GET'])
def rundetail():
# Get driver name list and order by first name
connection = getCursor()
sql=""" SELECT distinct driver.driver_id, driver.first_name, driver.surname
FROM driver
INNER JOIN car ON driver.car = car.car_num
INNER JOIN run ON driver.driver_id = run.dr_id
INNER JOIN course ON course.course_id = run.crs_id
order by driver.surname;"""
connection.execute(sql)
driverList = connection.fetchall()
connection = getCursor()
sql1 = """ SELECT driver.driver_id, driver.first_name, driver.surname, driver.age,
car.model, car.drive_class, run.crs_id, course.name,
run.run_num, run.seconds, run.cones, run.wd
FROM driver
INNER JOIN car ON driver.car = car.car_num
INNER JOIN run ON driver.driver_id = run.dr_id
INNER JOIN course ON course.course_id = run.crs_id"""
if request.method == 'POST':
# Get driver id that user selects from rundetail.html
driverId = request.form.get('driver')
elif request.method == 'GET':
# Get driver id that user clicks from driverlist.html
driverId = request.args.get('driverid')
#If driverId can be converted to an integer, convert to integer, otherwise set to None.
try:
driverId=int(driverId)
except:
driverId=None
defaulDriver = None
# if request.method == 'POST' and driverId is not None:
if driverId is not None:
sql2 = "where driver.driver_id = %s"
parameters = (driverId,)
defaulDriver = driverId
else:
sql2 = ""
parameters = ()
# Order by course id
sql3 = "ORDER BY run.crs_id;"""
# Combine all of the SQL parts into one SQL string.
# SQL2 will be "" if no value passed.
# Spaces avoid errors if no space between the strings.
sql = sql1 + ' ' + sql2 + ' ' +sql3
connection.execute(sql, parameters)
runDetail = connection.fetchall()
# Calculate the Run Total
runDetailUpdate = runsCalculate(runDetail)
# Debug print
for list in runDetailUpdate:
print(list)
return render_template("rundetail.html", run_detail = runDetailUpdate, driver_List = driverList, defaul_driver = defaulDriver)
@app.route("/overall", methods=['GET'])
def overall():
# Get driver name list and order by first name
connection = getCursor()
sql=""" SELECT distinct driver.driver_id, driver.first_name, driver.surname
FROM driver
INNER JOIN car ON driver.car = car.car_num
INNER JOIN run ON driver.driver_id = run.dr_id
INNER JOIN course ON course.course_id = run.crs_id
order by driver.surname;"""
connection.execute(sql)
driverList = connection.fetchall()
connection = getCursor()
sql1 = """ SELECT driver.driver_id, driver.first_name, driver.surname, driver.age,
car.model, car.drive_class, run.crs_id, course.name,
run.run_num, run.seconds, run.cones, run.wd
FROM driver
INNER JOIN car ON driver.car = car.car_num
INNER JOIN run ON driver.driver_id = run.dr_id
INNER JOIN course ON course.course_id = run.crs_id"""
if request.method == 'POST':
# Get driver id that user selects from rundetail.html
driverId = request.form.get('driver')
elif request.method == 'GET':
# Get driver id that user clicks from driverlist.html
driverId = request.args.get('driverid')
#If driverId can be converted to an integer, convert to integer, otherwise set to None.
try:
driverId=int(driverId)
except:
driverId=None
defaulDriver = None
# if request.method == 'POST' and driverId is not None:
if driverId is not None:
sql2 = "where driver.driver_id = %s"
parameters = (driverId,)
defaulDriver = driverId
else:
sql2 = ""
parameters = ()
# Order by course id
sql3 = "ORDER BY run.crs_id;"""
# Combine all of the SQL parts into one SQL string.
# SQL2 will be "" if no value passed.
# Spaces avoid errors if no space between the strings.
sql = sql1 + ' ' + sql2 + ' ' +sql3
connection.execute(sql, parameters)
runDetail = connection.fetchall()
# Calculate the Run Total
runDetailUpdate = runsCalculate(runDetail)
# Calculate the Overall Result
overallResults = overallCalculate(runDetailUpdate)
# Debug print
for list in overallResults:
print(list)
return render_template("overall.html", run_detail = overallResults, driver_List = driverList, defaul_driver = defaulDriver)
@app.route("/runedit", methods=['POST','GET'])
def runedit():
# Get driver name list and order by first name
connection = getCursor()
sql=""" SELECT distinct driver.driver_id, driver.first_name, driver.surname
FROM driver
INNER JOIN car ON driver.car = car.car_num
INNER JOIN run ON driver.driver_id = run.dr_id
INNER JOIN course ON course.course_id = run.crs_id
order by driver.surname;"""
connection.execute(sql)
driverList = connection.fetchall()
# Get course list and order by course id
connection = getCursor()
sql=""" SELECT * FROM course order by course.course_id;"""
connection.execute(sql)
courseList = connection.fetchall()
connection = getCursor()
sql1 = """ SELECT driver.driver_id, driver.first_name, driver.surname, driver.age,
car.model, car.drive_class, run.crs_id, course.name,
run.run_num, run.seconds, run.cones, run.wd
FROM driver
INNER JOIN car ON driver.car = car.car_num
INNER JOIN run ON driver.driver_id = run.dr_id
INNER JOIN course ON course.course_id = run.crs_id"""
# Get driver id that user selects from runedit.html
driverId = request.form.get('driver')
# Get course id that user selects from runedit.html
courseId = request.form.get('course')
#If driverId can be converted to an integer, convert to integer, otherwise set to None.
try:
driverId=int(driverId)
except:
driverId=None
#If courseId is not None and course id, then convert it to None.
if courseId is not None:
if len(courseId)>1:
courseId=None
defaulDriver = None
defaulCourse = None
if driverId is not None:
sql2 = "where driver.driver_id = %s"
parameters = (driverId,)
defaulDriver = driverId
elif courseId is not None:
sql2 = "where course.course_id = %s"
parameters = (courseId,)
defaulCourse = courseId
else:
sql2 = ""
parameters = ()
# Order by course id
sql3 = "ORDER BY run.crs_id, driver.surname, driver.first_name, run.run_num;"""
# Combine all of the SQL parts into one SQL string.
# SQL2 will be "" if no value passed.
# Spaces avoid errors if no space between the strings.
sql = sql1 + ' ' + sql2 + ' ' +sql3
connection.execute(sql, parameters)
runDetail = connection.fetchall()
# Calculate the Run Total
runDetailUpdate = runsCalculate(runDetail)
# Debug print
# for list in runDetailUpdate:
# print(list)
# for list in courseList:
# print(list)
return render_template("runedit.html", run_detail = runDetailUpdate, driver_List = driverList, course_List = courseList, defaul_driver = defaulDriver, defaul_course = defaulCourse)
@app.route("/runedit/update", methods=["POST"])
def runeditupdate():
driverid = request.form.get('driverid')
courseid = request.form.get('courseid')
runnum = request.form.get('runnum')
time = request.form.get('time')
cone = request.form.get('cone')
wd = request.form.get('wd')
error = ''
connection = getCursor()
sql = """ UPDATE run
SET seconds = %s, cones = %s, wd = %s
WHERE dr_id = %s AND crs_id = %s AND run_num = %s;"""
parameters = (time,cone,wd,driverid,courseid,runnum,)
try:
connection.execute(sql,parameters)
connection.fetchall()
flash([1, 'Edit Successfully! Driver ID: '+driverid+' - Course ID: '+courseid+' - Run Num: '+runnum])
except Exception as ex:
print(ex)
error = 'Invalid Input'
flash([0, 'Edit Unsuccessfully. Driver ID: '+driverid+' - Course ID: '+courseid+' - Run Num: '+runnum])
return redirect(url_for('runedit'))
@app.route("/driveradd")
def driveradd():
# Get car list and order by car_num
connection = getCursor()
sql=""" SELECT * FROM car order by car.car_num;"""
connection.execute(sql)
carList = connection.fetchall()
return render_template("driveradd.html", car_list= carList)
@app.route("/driveraddnext", methods=["POST"])
def driveraddnext():
# Get firstname/surname/carId from driveradd.html
driverName = [request.form.get('firstname'),request.form.get('surname')]
carStr = request.form.get('car')
carId=carStr.split(" - ")[0]
carModelClass=carStr.split(" - ")[1]
car = [carId, carModelClass]
driverType = request.form.get('driverType')
nowDate = datetime.datetime.now()
lastDate = nowDate + datetime.timedelta(days = -1)
lastYear = lastDate.year
lastMonth = lastDate.month
lastDay = lastDate.day
# Get caregiver list and order by surname
connection = getCursor()
sql=""" SELECT driver.driver_id, driver.first_name, driver.surname
FROM driver
where driver.age > 25 or driver.age is null
order by driver.surname, driver.first_name;"""
connection.execute(sql)
caregiverList = connection.fetchall()
match driverType:
case "option25":
return render_template('driveraddnonjunior.html', driverName=driverName,car=car)
case "option16_25":
oldYear = lastYear - 25
newYear = lastYear - 16
minDate = str(oldYear)+"-"+str(lastMonth)+"-"+str(nowDate.day)
maxDate = str(newYear)+"-"+str(lastMonth)+"-"+str(lastDay)
return render_template("driveraddbirthday.html", driverName=driverName,car=car,date=[minDate,maxDate])
case "option12_16":
oldYear = lastYear - 16
newYear = lastYear - 12
minDate = str(oldYear)+"-"+str(lastMonth)+"-"+str(nowDate.day)
maxDate = str(newYear)+"-"+str(lastMonth)+"-"+str(lastDay)
return render_template("driveraddunder16.html", driverName=driverName,car=car,date=[minDate,maxDate],caregiver_list = caregiverList)
@app.route("/driveraddnonjunior", methods=['POST'])
def driveraddnonjunior():
# Get course id list
connection = getCursor()
sql=""" SELECT course.course_id FROM course;"""
connection.execute(sql)
courseList = connection.fetchall()
# Get firstname/surname/carId from driveradd.html
firstname = request.form.get('firstname')
surname = request.form.get('surname')
carId = int(request.form.get('car'))
try:
# Insert driver data into driver table
connection = getCursor()
sql1 = """ INSERT INTO driver (first_name, surname, car)
VALUES (%s, %s, %s);"""
sql2 = """ SELECT max(driver_id) FROM driver;"""
parameters = (firstname,surname,carId,)
connection.execute(sql1,parameters)
connection.execute(sql2)
driverId = connection.fetchall()
# Insert init run data into run table
connection = getCursor()
sql = """ INSERT INTO run (dr_id, crs_id, run_num, seconds, cones, wd)
VALUES (%s, %s, %s, %s, %s, %s);"""
for courseId in courseList:
for i in range(1,3):
parameters = (driverId[0][0], courseId[0], i, None, None, 0,)
connection.execute(sql,parameters)
print(parameters)
flash([1, 'Add Driver Successfully! Driver ID: '+str(driverId[0][0])])
except Exception as ex:
print(ex)
flash([0, 'Add Driver Unsuccessfully. Driver ID: '+str(driverId[0][0])])
return redirect(url_for('searchdriverfilter',driver_id = driverId[0][0], driver_name = firstname +" "+ surname))
@app.route("/driveraddjunior", methods=["POST"])
def driveraddjunior():
# Get course id list
connection = getCursor()
sql=""" SELECT course.course_id FROM course;"""
connection.execute(sql)
courseList = connection.fetchall()
# Get firstname/surname/carId from driveraddbirthday.html
firstname = request.form.get('firstname')
surname = request.form.get('surname')
carId = int(request.form.get('car'))
inputbirthday = request.form.get('birthday')
ageBirthday = ageCalculate(inputbirthday)
birthday = ageBirthday['birthday']
age = ageBirthday['age']
try:
# Insert driver data into driver table
connection = getCursor()
sql1 = """ INSERT INTO driver (first_name, surname, date_of_birth, age, car)
VALUES (%s, %s, %s, %s, %s);"""
sql2 = """ SELECT max(driver_id) FROM driver;"""
parameters = (firstname, surname, birthday, age, carId,)
connection.execute(sql1,parameters)
connection.execute(sql2)
driverId = connection.fetchall()
# Insert init run data into run table
connection = getCursor()
sql = """ INSERT INTO run (dr_id, crs_id, run_num, seconds, cones, wd)
VALUES (%s, %s, %s, %s, %s, %s);"""
for courseId in courseList:
for i in range(1,3):
parameters = (driverId[0][0], courseId[0], i, None, None, 0,)
connection.execute(sql,parameters)
print(parameters)
flash([1, 'Add Driver Successfully! Driver ID: '+str(driverId[0][0])])
except Exception as ex:
print(ex)
flash([0, 'Add Driver Unsuccessfully. Driver ID: '+str(driverId[0][0])])
return redirect(url_for('searchdriverfilter',driver_id = driverId[0][0], driver_name = firstname +" "+ surname))
@app.route("/driveraddunder16", methods=["POST"])
def driveraddunder16():
# Get course id list
connection = getCursor()
sql=""" SELECT course.course_id FROM course;"""
connection.execute(sql)
courseList = connection.fetchall()
# Get firstname/surname/carId from driveradd.html
firstname = request.form.get('firstname')
surname = request.form.get('surname')
carId = int(request.form.get('car'))
caregiver = int(request.form.get('caregiver'))
inputbirthday = request.form.get('birthday')
ageBirthday = ageCalculate(inputbirthday)
birthday = ageBirthday['birthday']
age = ageBirthday['age']
try:
# Insert driver data into driver table
connection = getCursor()
sql1 = """ INSERT INTO driver (first_name, surname, date_of_birth, age, caregiver, car)
VALUES (%s, %s, %s, %s, %s, %s);"""
sql2 = """ SELECT max(driver_id) FROM driver;"""
parameters = (firstname, surname, birthday, age, caregiver, carId,)
connection.execute(sql1,parameters)
connection.execute(sql2)
driverId = connection.fetchall()
# Insert init run data into run table
connection = getCursor()
sql = """ INSERT INTO run (dr_id, crs_id, run_num, seconds, cones, wd)
VALUES (%s, %s, %s, %s, %s, %s);"""
for courseId in courseList:
for i in range(1,3):
parameters = (driverId[0][0], courseId[0], i, None, None, 0,)
connection.execute(sql,parameters)
print(parameters)
flash([1, 'Add Driver Successfully! Driver ID: '+str(driverId[0][0])])
except Exception as ex:
print(ex)
flash([0, 'Add Driver Unsuccessfully. Driver ID: '+str(driverId[0][0])])
return redirect(url_for('searchdriverfilter',driver_id = driverId[0][0], driver_name = firstname +" "+ surname))
@app.route("/searchdriver")
def searchdriver():
connection = getCursor()
sql = """ SELECT d1.driver_id, d1.first_name, d1.surname, d1.age,
car.model, car.drive_class, d2.first_name, d2.surname FROM driver d1
INNER JOIN car ON d1.car = car.car_num
LEFT JOIN driver d2 ON d1.caregiver = d2.driver_id
ORDER BY d1.surname;"""
connection.execute(sql)
driverList = connection.fetchall()
for list in driverList:
print(list)
return render_template("driversearch.html", driver_list = driverList)
@app.route("/searchdriver/filter", methods=["POST","GET"])
def searchdriverfilter():
driverNameAdd = request.args.get('driver_name')
driverId = request.args.get('driver_id')
driverNameSearch = request.form.get('driver')
connection = getCursor()
if driverId != None:
driverName = driverNameAdd
sql = """ SELECT d1.driver_id, d1.first_name, d1.surname, d1.age,
car.model, car.drive_class, d2.first_name, d2.surname
FROM driver d1
INNER JOIN car ON d1.car = car.car_num
LEFT JOIN driver d2 ON d1.caregiver = d2.driver_id
WHERE d1.driver_id = %s
ORDER BY d1.surname, d1.first_name;"""
parameters = (driverId,)
else:
driverName = driverNameSearch
sql = """ SELECT d1.driver_id, d1.first_name, d1.surname, d1.age,
car.model, car.drive_class, d2.first_name, d2.surname
FROM driver d1
INNER JOIN car ON d1.car = car.car_num
LEFT JOIN driver d2 ON d1.caregiver = d2.driver_id
WHERE concat(d1.first_name,' ' ,d1.surname) like %s
ORDER BY d1.surname, d1.first_name;"""
parameters = (f'%{driverName}%',)
connection.execute(sql,parameters)
driverList = connection.fetchall()
for list in driverList:
print(list)
return render_template("driversearch.html", driver_list = driverList, driver_name = driverName)