-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
1702 lines (1630 loc) · 75.4 KB
/
main.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
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# importing required Modules
from flask import Flask, render_template, request, redirect, Response
from flask_mail import Mail, Message
import random
import pymysql
import sqlite3
import os
import io
import csv
from datetime import datetime
import matplotlib.pyplot as plt
import statistics
# Global Variables
global teacher_Id, student_Id, quiz_Id
global presentQuestion
global totalQuestions
global Questions
global eTime
global flag
global random_number
global mail_id
global teacherName
teacher_Id = None
student_Id = None
quiz_Id = None
global flag
flag = 0
# Initializing Flask Application
app = Flask(__name__)
# Fetching the Password of the Database from the Txt file
PASSWORD = ''
with open('Details.txt', 'r') as f:
PASSWORD = f.readline()
# Function to generate a random string of length 4
def CreateQuizId():
lst = []
for i in range(4):
lst.append(str(chr(random.randint(65, 90))))
print(lst)
QuizId = ""
for x in lst:
QuizId += x
return QuizId
# Application Default Route
@app.route("/", methods=["GET", "POST"])
def index():
# Connecting to MySQL Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
# If Exception occurred redirecting to default route
except Exception as E:
print(E)
return render_template("index.html", noNetwork=True)
cur = conn.cursor()
cur.execute('''SELECT PASSWORD, PORT, SEREVER, USERNAME, DB FROM EMAIL WHERE PORT=587''')
data = cur.fetchall()[0]
# Configuring the Mail Credentials from Database
app.config["MAIL_PASSWORD"] = data[0]
app.config["MAIL_PORT"] = data[1]
app.config["MAIL_SERVER"] = data[2]
app.config["MAIL_DEFAULT_SENDER"] = data[3]
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = data[4]
conn.commit()
conn.close()
return render_template("index.html")
# Login route
@app.route("/login", methods=["POST", "GET"])
def login():
global presentQuestion, totalQuestions, Questions, flag
global teacher_Id, student_Id, quiz_Id, teacherName, eTime
uName = request.form.get("username")
pwd = request.form.get("password")
name = ""
quizId = request.form.get("quizId")
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("index.html", uName=uName, pwd=pwd, quizId=quizId, noNetwork=True)
cur = conn.cursor()
# Teacher login
if quizId == "" or quizId is None:
# Selecting Details of teacher with their Email-Id
cur.execute('''SELECT * FROM TEACHER WHERE EMAIL='{}' '''.format(uName))
details = cur.fetchall()
# Committing And Closing Database Connection
conn.commit()
conn.close()
print(details)
if details and (quizId == "" or quizId is None):
name = details[0][1] + " " + details[0][2]
teacherName = name
Password = details[0][6]
# If Password Matched
if pwd == Password:
teacher_Id = uName
return render_template("teacherHome.html", username=teacherName)
# If Password is Wrong
else:
return render_template("teacher.html", wrngPwd=True, uName=uName, pwd=pwd)
# If Teacher do not Exist
else:
return render_template("teacher.html", userNotFound=True, uName=uName, pwd=pwd)
# Student Login
if quizId != "" and quizId is not None:
# Selecting Student Details from the Database
cur.execute('''SELECT * FROM STUDENT WHERE QUIZ_ID='{}' AND EMAIL='{}' '''.format(quizId, uName))
details = cur.fetchall()
conn.commit()
# If Student Exists
if details:
cur.execute('''SELECT * FROM STUDENT WHERE QUIZ_ID='{}' AND EMAIL='{}' '''.format(quizId, uName))
details = cur.fetchall()
conn.commit()
if details[0][0] == uName:
# If Password Matched
if pwd == details[0][2]:
print("Password Matched...")
student_Id = uName
quiz_Id = quizId
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
# Fetching the Quiz Details from the DataBase
cur.execute('''SELECT * FROM QUIZ WHERE QUIZ_ID='{}' '''.format(quizId))
d = cur.fetchall()
conn.commit()
conn.close()
# Flag to check whether the student have done malpractice or not
if int(flag) <= 2:
pass
else:
return redirect("submitted")
student_Id = uName
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
# Fetching Student Details from the Database
cur.execute(
'''SELECT NAME,EMAIL FROM STUDENT WHERE QUIZ_ID='{}' AND EMAIL='{}' '''.format(quizId, uName))
student = cur.fetchall()
data = d[0][3].split("T")
startDate = data[0]
print(startDate)
startTime = data[1]
print(startTime)
endData = d[0][4].split("T")
endTime = endData[1]
print(endTime)
startHrs = startTime[:2]
startMins = startTime[3:]
endHrs = endTime[:2]
endMins = endTime[3:]
# If Quiz Date Matched
if datetime.now().strftime("%Y-%m-%d") == startDate:
# If Student Logins in Time
if startHrs == datetime.now().strftime("%H") and startMins <= datetime.now().strftime("%M"):
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
cur.execute('''SELECT FLAG FROM STUDENT WHERE QUIZ_ID='{}' AND EMAIL='{}' '''.format(quizId,
uName))
# Checking Whether the Student has submitted the quiz before or not
if cur.fetchall()[0][0] == "S":
something = "Student, you have already submitted your quiz. "
return render_template("studentlogin.html", data=d, student=student,
something=something)
# If not Submitted directing to the Instructions Page
else:
return render_template("instructions.html", data=d, student=student)
elif startHrs < datetime.now().strftime("%H") < endHrs:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
cur.execute('''SELECT FLAG FROM STUDENT WHERE QUIZ_ID='{}' AND EMAIL='{}' '''.format(quizId,
uName))
if cur.fetchall()[0][0] == "S":
# print(cur.fetchall()[0][0])
something = "Student, you have already submitted your quiz. "
return render_template("studentlogin.html", data=d, student=student,
something=something)
else:
return render_template("instructions.html", data=d, student=student)
pass
elif endHrs == datetime.now().strftime("%H") and endMins > datetime.now().strftime("%M"):
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
cur.execute(
'''SELECT FLAG FROM STUDENT WHERE QUIZ_ID='{}' AND EMAIL='{}' '''.format(quizId, uName))
if cur.fetchall()[0][0] == "S":
something = "Student, you have already submitted your quiz. "
return render_template("studentlogin.html", data=d, student=student,
something=something)
else:
return render_template("instructions.html", data=d, student=student)
pass
else:
something = "quiz has ended"
return render_template("studentlogin.html", data=d, something=something, student=student)
else:
something = "quiz has ended"
return render_template("studentlogin.html", data=d, student=student, something=something)
# If Password is Wrong
else:
return render_template("index.html", wrngPwd=True, uName=uName, pwd=pwd, quizId=quizId)
# If Student is not invited to the particular Quiz
else:
return render_template("index.html", userNotFound=True, uName=uName, pwd=pwd, quizId=quizId)
# If the Quiz does not Exist or Expire
else:
return render_template("index.html", invalidQuiz=True, uName=uName, pwd=pwd, quizId=quizId)
# Route to the Exam
@app.route("/startquiz", methods=["POST", "GET"])
def startquiz():
global presentQuestion, totalQuestions, Questions, flag
global teacher_Id, student_Id, quiz_Id, eTime
uName = request.form.get("email")
quizId = request.form.get("QuizId")
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("index.html", noNetword=True)
cur = conn.cursor()
cur.execute('''SELECT * FROM STUDENT WHERE QUIZ_ID='{}' AND EMAIL='{}' '''.format(quizId, uName))
details = cur.fetchall()
conn.commit()
pwd = details[0][2]
cur.execute('''SELECT * FROM QUIZ WHERE QUIZ_ID='{}' '''.format(quizId))
d = cur.fetchall()
conn.commit()
conn.close()
if int(flag) <= 2:
pass
else:
return redirect("submitted")
student_Id = uName
data = d[0][3].split("T")
startDate = data[0]
startTime = data[1].split(":")
startTime = (startTime[0] + startTime[1])
endData = d[0][4].split("T")
endDate = endData[0]
endTime1 = endData[1]
endTime = endData[1].split(":")
endTime = (endTime[0] + endTime[1])
message = "Quiz {} is Scheduled to start at {} {}\nIt will end at {} {}".format(quizId, data[0], data[1],
endData[0], endData[1])
print(message)
endTime = endData[0][5:7] + " " + endData[0][8:10] + ", " + endData[0][0:4] + " " + endData[1]
print(endTime)
eTime = endTime
quiz_Id = quizId
print("i came here")
c1 = c2 = c3 = c4 = ""
Questions = [[1, "Q1", "A", "B", "C", "D"],
[2, "Q2", "E", "F", "G", "H"],
[3, "Q3", "I", "J", "K", "L"]]
totalQuestions = 2
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
cur.execute('''SELECT Q_NO, QUESTION, OP_1, OP_2, OP_3, OP_4 FROM QUESTIONS WHERE QUIZ_ID='{}' '''.format(
quizId))
Questions = cur.fetchall()
conn.commit()
conn.close()
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
cur.execute('''SELECT NO_OF_QUESTIONS FROM QUIZ WHERE QUIZ_ID = '{}' '''.format(quizId))
totalQuestions = cur.fetchall()
print(totalQuestions)
totalQuestions = totalQuestions[0][0]
presentQuestion = 0
conn = sqlite3.connect("Answers.sqlite")
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS ANSWERS(QUESTION_NUMBER TEXT, ANSWER TEXT)''')
conn.commit()
for i in range(0, totalQuestions):
cur.execute('''SELECT * FROM ANSWERS WHERE QUESTION_NUMBER =?''', (i,))
rows = cur.fetchall()
if rows:
continue
cur.execute('''INSERT OR IGNORE INTO ANSWERS VALUES(?, ?)''', (i, None))
conn.commit()
conn.close()
conn = sqlite3.connect("Answers.sqlite")
cur = conn.cursor()
cur.execute('''SELECT ANSWER FROM ANSWERS WHERE QUESTION_NUMBER=?''', (0,))
ans = cur.fetchall()
if ans:
ans = ans[0][0]
if ans == '1':
c1 = "checked"
elif ans == '2':
c2 = "checked"
elif ans == '3':
c3 = "checked"
elif ans == '4':
c4 = "checked"
return render_template("StudentHome.html", endTime=endTime, username=uName, Questions=Questions,
total=totalQuestions, qno=0,
Loop=[x for x in range(1, totalQuestions + 1)],
c1=c1, c2=c2, c3=c3, c4=c4)
# Signup Route--> To Create a Teacher Account
@app.route("/signup", methods=["GET", "POST"])
def singup():
if request.method == "GET":
return render_template("signup.html")
else:
# Getting the Details entered by the teacher
emailId = request.form.get("emailId")
fName = request.form.get("fName")
lName = request.form.get("lName")
mobile = request.form.get("mobile")
subject = request.form.get("subject")
institutionName = request.form.get("institutionName")
signupPassword = request.form.get("signupPassword")
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
cur = conn.cursor()
cur.execute('''SELECT EMAIL FROM TEACHER WHERE EMAIL='{}' '''.format(emailId))
users = cur.fetchall()
# Checking if the user existence with same email
if users:
return render_template("signup.html", specialCharacter=False, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword, userExists=True)
except Exception as E:
print(E)
return render_template("signup.html", specialCharacter=False, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword, noNetwork=True)
# Checking the mobile Number they have entered
try:
mobile = int(mobile)
except ValueError:
print(emailId, fName, lName, mobile, subject, institutionName, signupPassword)
return render_template("signup.html", valueOfMobile=False, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword)
# Checking the mobile number they have entered
if (mobile % 1000000000) == mobile:
return render_template("signup.html", invalidMobile=True, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword)
if "~" in signupPassword:
return render_template("signup.html", invalidChar=True, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword)
# Checking the Password length
if len(signupPassword) < 8:
return render_template("signup.html", lengthOfPassword=False, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword)
# Checking for Numeric Character in the password
count = 0
for i in range(48, 58):
if chr(i) in signupPassword:
count += 1
if count == 0:
return render_template("signup.html", numericCharacter=False, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword)
# Checking for Uppercase Character in the password
count = 0
for i in range(65, 91):
if chr(i) in signupPassword:
count += 1
if count == 0:
return render_template("signup.html", upperCase=False, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword)
# Checking for Special Character int the Password
count = 0
for i in range(33, 48):
if chr(i) in signupPassword:
count += 1
for i in range(58, 65):
if chr(i) in signupPassword:
count += 1
for i in range(91, 97):
if chr(i) in signupPassword:
count += 1
for i in range(123, 126):
if chr(i) in signupPassword:
count += 1
if count == 0:
return render_template("signup.html", specialCharacter=False, emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword)
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("signup.html", emailId=emailId, fName=fName, lName=lName,
mobile=mobile, subject=subject, institutionName=institutionName,
signupPassword=signupPassword, noNetwork=True)
# Inserting the user Details into the Database
cur = conn.cursor()
sql = '''INSERT INTO TEACHER VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}')'''.format(emailId, fName, lName,
mobile, subject,
institutionName,
signupPassword)
cur.execute(sql)
conn.commit()
conn.close()
# Sending mail to user with their login id and password
mail = Mail(app)
message = Message("You are registered Mr {}".format(fName),
recipients=[emailId],
body="Hello {} {}\nUsername : {}\nPassword : {}".format(fName, lName, emailId,
signupPassword))
# To add attachment
# with app.open_resource("hello.txt") as fp:
# message.attach("testos.py", 'application/octet-stream', fp.read())
mail.send(message)
return render_template("index.html", creationValue=True)
# Teacher Home Route
@app.route("/teacherHome", methods=["GET", "POST"])
def teacherHome():
global teacherName
return render_template("teacherHome.html", username=teacherName)
# Route to clear files created in local Database
@app.route("/clear")
def clear():
global totalQuestions, teacher_Id, teacherName
for ques in range(1, totalQuestions + 1):
if os.path.exists("static/Pie_Question{}.png".format(ques)):
os.remove("static/Pie_Question{}.png".format(ques))
if os.path.exists("static/BarChartFrequencyOfMarksByStudents.png"):
os.remove('static/BarChartFrequencyOfMarksByStudents.png')
return redirect("/teacherHome")
# Route to create Quiz
@app.route("/CreateQuiz", methods=["GET", "POST"])
def createQuiz():
global quiz_Id, teacher_Id, teacherName
print("Hello", teacher_Id)
if request.method == "GET":
return render_template("TeacherCreateQuiz.html")
else:
# Checking whether the user have an Internet connection or not
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("TeacherCreateQuiz.html", username=teacherName, noNetwork=True)
cur = conn.cursor()
# Generating a random unique Quiz id
QuizId = ''
while True:
QuizId = CreateQuizId()
cur.execute('''SELECT * FROM QUIZ WHERE QUIZ_ID='{}' '''.format(QuizId))
quizes = cur.fetchall()
if not quizes:
break
quiz_Id = QuizId
# Getting the value from the user
noOfQues = request.form.get("NoOfQuestions")
startTime = request.form.get("startTime")
print(startTime)
endTime = request.form.get("endTime")
print(endTime)
cMarks = request.form.get("crctAns")
wMarks = request.form.get("wrngAns")
instructions = request.form.get("instructions")
print(quiz_Id, noOfQues, startTime, endTime, cMarks, wMarks, instructions)
# Inserting the Quiz Details into the Database
cur.execute('''INSERT INTO QUIZ VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')'''
.format(teacher_Id, QuizId, noOfQues, startTime, endTime, instructions, cMarks, wMarks))
conn.commit()
conn.close()
return render_template("teacherHome.html", quizId=QuizId, quizAdded=True, username=teacherName)
# Route to Modify the Quiz
@app.route("/modifyQuiz", methods=["POST"])
def modifyQuiz():
global teacher_Id, teacherName
# Checking whether the user having an internet Connection or not
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("modifyQuiz.html", username=teacherName, noNetwork=True)
cur = conn.cursor()
# Fetching all quiz's of the Teacher
cur.execute('''SELECT QUIZ_ID FROM QUIZ WHERE TEACHER='{}' '''.format(teacher_Id))
data = cur.fetchall()
print(data)
print(teacher_Id)
conn.commit()
conn.close()
return render_template("modifyQuiz.html", data=data, username=teacherName)
# Route to add Questions into the particular quiz
@app.route("/add", methods=["POST"])
def addQuestion():
global teacherName, teacher_Id
# Getting the Details entered by the user
quizId = request.form.get("QuizId")
quesNo = request.form.get("QuestionNumber")
ques = request.form.get("Question")
op1 = request.form.get("Option1")
op2 = request.form.get("Option2")
op3 = request.form.get("Option3")
op4 = request.form.get("Option4")
crctAns = request.form.get("CorrectAnswer")
# Correcting should be either 1 or 2 or 3 or 4
if 1 <= int(crctAns) <= 4:
pass
else:
return render_template("modifyQuiz.html", error=True)
print(quizId)
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("modifyQuiz.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
cur.execute('''SELECT NO_OF_QUESTIONS FROM QUIZ WHERE QUIZ_ID='{}' '''.format(quizId))
totQuestions = cur.fetchall()[0][0]
cur.execute('''SELECT COUNT(*) FROM QUESTIONS WHERE QUIZ_ID='{}' '''.format(quizId))
questions = cur.fetchall()[0][0]
# Checking if the questions exceeding the total no of questions or not
if int(questions) >= int(totQuestions):
return render_template("modifyQuiz.html", full=True, username=teacherName)
# Inserting the Question into the Database
cur.execute('''INSERT INTO QUESTIONS VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')
'''.format(quizId, quesNo, ques, op1, op2, op3, op4, crctAns))
conn.commit()
conn.close()
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("modifyQuiz.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
# Fetching the Quiz id's of the user
cur.execute('''SELECT QUIZ_ID FROM QUIZ WHERE TEACHER='{}' '''.format(teacher_Id))
data = cur.fetchall()
print(data)
print(teacher_Id)
conn.commit()
conn.close()
return render_template("modifyQuiz.html", questionAdded=True, data=data, username=teacherName)
# Route to update a Question
@app.route("/update", methods=["POST"])
def updateQuestion():
global teacherName, teacher_Id
# Getting the values entered by the user
quizId = request.form.get("QuizId")
quesNo = request.form.get("QuestionNumber")
ques = request.form.get("Question")
op1 = request.form.get("Option1")
op2 = request.form.get("Option2")
op3 = request.form.get("Option3")
op4 = request.form.get("Option4")
crctAns = request.form.get("CorrectAnswer")
print(quizId)
# Checking for stable internet connection and Connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("modifyQuiz.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
# Updating the Question in the Database
cur.execute('''UPDATE QUESTIONS SET QUESTION='{}', OP_1='{}', OP_2='{}', OP_3='{}', OP_4='{}', CRCT_ANS='{}' WHERE
QUIZ_ID='{}' AND Q_NO='{}' '''.format(ques, op1, op2, op3, op4, crctAns, quizId, quesNo))
conn.commit()
conn.close()
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("modifyQuiz.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
# Fetching the Quiz id's of the particular user
cur.execute('''SELECT QUIZ_ID FROM QUIZ WHERE TEACHER='{}' '''.format(teacher_Id))
data = cur.fetchall()
print(data)
print(teacher_Id)
# Closing the Database Connection
conn.commit()
conn.close()
return render_template("modifyQuiz.html", questionUpdated=True, data=data, username=teacherName)
# Route to Delete A Question
@app.route("/delete", methods=["POST"])
def deleteQuestion():
global teacherName, teacher_Id
# Getting the Values Entered by the user
quizId = request.form.get("QuizId")
quesNo = request.form.get("QuestionNumber")
# Checking for a stable internet Connection and connecting to the database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("modifyQuiz.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
# Deleting the Question from the Database
cur.execute('''DELETE FROM QUESTIONS WHERE QUIZ_ID='{}' AND Q_NO='{}' '''.format(quizId, quesNo))
# Closing the Database Connection
conn.commit()
conn.close()
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("modifyQuiz.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
cur.execute('''SELECT QUIZ_ID FROM QUIZ WHERE TEACHER='{}' '''.format(teacher_Id))
data = cur.fetchall()
print(data)
print(teacher_Id)
conn.commit()
conn.close()
return render_template("modifyQuiz.html", questionDeleted=True, data=data, username=teacherName)
# Route to Show all the Questions in the Quiz
@app.route("/showAll", methods=["POST"])
def showAllQuestion():
global teacherName, teacher_Id
# Getting the Quiz id entered by the user
quizId = request.form.get("QuizId")
# Checking for a stable connection and connecting to the database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
# If no Network
except Exception as E:
print(E)
return render_template("showAll.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
# Fetching the Questions from the Database
cur.execute('''SELECT * FROM QUESTIONS WHERE QUIZ_ID='{}' '''.format(quizId))
data = cur.fetchall()
# Fetching the Column Names from the Database
cur.execute('''SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='DBMSFLASKPROJECT'
AND `TABLE_NAME`='QUESTIONS';''')
cols = cur.fetchall()
cols = (cols[7][0], cols[5][0], cols[6][0], cols[1][0], cols[2][0], cols[3][0], cols[4][0], cols[0][0])
print(cols)
conn.commit()
conn.close()
print(data)
return render_template("showAll.html", data=data, cols=cols)
# Route to Invite the Students
@app.route("/inviteStudents", methods=["GET", "POST"])
def inviteStudents():
global teacher_Id, quiz_Id, student_Id, teacherName
teacher_Id = teacher_Id
if request.method == "GET":
# Checking for a stable internet connection and Connecting to the database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
# If no Network
except Exception as E:
print(E)
return redirect("/teacherHome")
cur = conn.cursor()
# Fetching the Quiz id's of that user
cur.execute('''SELECT QUIZ_ID FROM QUIZ WHERE TEACHER='{}' '''.format(teacher_Id))
data = cur.fetchall()
print(data)
conn.commit()
conn.close()
return render_template("studentInvite.html", data=data, username=teacher_Id)
else:
# Checking for a stable internet Connection and connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return redirect("/teacherHome")
# Getting the Quiz Id entered by the User
q_Id = request.form.get("QuizId")
# Getting the File uploaded by the User
file = request.files['file']
# Saving the File in the current directory to access the data
file.save(file.filename)
print(file)
print(file.filename)
# Opening the file in read mode
File = open(file.filename, "r")
data = File.readlines()
print(data)
email = []
name = []
# Getting the email and names separated
for line in data[1:]:
line = line.split(",")
email.append(line[0])
name.append(line[1][:-1])
print(email)
print(name)
for m, n in zip(email, name):
pw = []
# Generating a random Password for each student in the list
for i in range(10):
pw.append(chr(random.randint(33, 122)))
password = ""
for x in pw:
password += x
print(m)
print(password)
cur = conn.cursor()
# Inserting Student Details into the Database
cur.execute(''' INSERT INTO STUDENT VALUES('{}','{}','{}','{}', '{}', '{}') '''.format(m, n, password, q_Id,
None, 0))
conn.commit()
mail = Mail(app)
# Initializing message with the below details
message = Message("You are registered as {}".format(n),
recipients=[m])
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return redirect("/teacherHome")
# Getting the Details of the Quiz from the Database
cur = conn.cursor()
cur.execute('''SELECT START_TIME, END_TIME FROM QUIZ WHERE QUIZ_ID='{}' '''.format(q_Id))
rows = cur.fetchall()
startTime = rows[0][0]
startTime = startTime.replace("T", " ")
endTime = rows[0][1]
endTime = endTime.replace("T", " ")
if int(startTime[14:]) < 55:
loginTime = startTime[:14] + str(int(startTime[14:]) + 5)
else:
loginTime = startTime[:11] + str(int(startTime[11:13]) + 1) + startTime[13:]
print(loginTime)
# Committing Changes to the Database
conn.commit()
# Adding Html to the mail
message.html = render_template("mail.html", quizId=q_Id, teacher=teacher_Id, student=n, startTime=startTime,
endTime=endTime, loginTime=loginTime, username=m, password=password)
# Sending mail to the Student
mail.send(message)
# Closing Database Connection
conn.close()
return render_template("teacherHome.html", username=teacherName)
# Route to view Results
@app.route("/viewResults", methods=["GET", "POST"])
def view_results():
global quiz_Id, teacher_Id, teacherName
if request.method == "GET":
# Checking for a stable connection and Connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return redirect("/teacherHome")
cur = conn.cursor()
# Fetching Quiz id's of that user
cur.execute('''SELECT QUIZ_ID FROM QUIZ WHERE TEACHER='{}' '''.format(teacher_Id))
data = cur.fetchall()
print(data)
return render_template("viewResults.html", username=teacherName, data=data)
# Getting the Quiz id entered by the user
quizId = request.form.get('QuizId')
if quizId:
quiz_Id = quizId
# Checking for a stable internet connection and connecting to the database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
# If no network
except Exception as E:
print(E)
return redirect("/teacherHome")
cur = conn.cursor()
# Fetching Student with their marks
cur.execute('''SELECT NAME,MARKS, FLAG FROM STUDENT WHERE QUIZ_ID='{}' ORDER BY NAME'''.format(quiz_Id))
results = cur.fetchall()
return render_template('view_results.html', data=results, quiz_Id=quiz_Id)
# Route to Search a Particular Student in the results list
@app.route("/searchstudent", methods=["GET", "POST"])
def searchstudent():
global quiz_Id
if request.method == "POST" or 1:
# Getting the student name of the student entered by the teacher
student_results = request.form['searchstudent']
print(quiz_Id)
# Checking for a stable connection and connecting to the database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return redirect("/teacherHome")
cur = conn.cursor()
# Selecting that student from the Database
cur.execute(
'''SELECT NAME,MARKS, FLAG FROM STUDENT WHERE NAME LIKE '%{}%' AND QUIZ_ID='{}' '''.format(student_results,
quiz_Id))
# If No Such Student Exists then displaying all students
results = cur.fetchall()
if len(results) == 0 or student_results == 'all':
# Checking for a stable connection and connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return redirect("/teacherHome")
cur = conn.cursor()
# Selecting all Students from the Database
cur.execute('''SELECT NAME,MARKS, FLAG FROM STUDENT WHERE QUIZ_ID='{}' '''.format(quiz_Id))
results = cur.fetchall()
return render_template('searchstudent.html', data=results, searched_student=student_results,
quiz_Id=quiz_Id)
return render_template('searchstudent.html', data=results, searched_student=student_results, quiz_Id=quiz_Id)
# Route to Download Results of a particular Quiz
@app.route("/download_data", methods=["GET", "POST"])
def download_data():
global quiz_Id
if request.method == "POST" or 1:
conn = ''
# Checking for a stable connection and connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as e:
print(e)
cur = conn.cursor()
print(quiz_Id[0])
# Fetching the Student marks from the Database
cur.execute('''SELECT NAME,MARKS, FLAG FROM STUDENT WHERE QUIZ_ID='{}' '''.format(quiz_Id))
results = cur.fetchall()
# Creating a file
output = io.StringIO()
# Writer to write data to the file
writer = csv.writer(output)
line = ['Student Name', 'Student Marks', 'FLAG']
writer.writerow(line)
# Writing Data of the Students into the file
for row in results:
line = [str(row[0]), row[1], row[2]]
writer.writerow(line)
output.seek(0)
return Response(output, mimetype="text/csv",
headers={"content-Disposition": "attachment;filename=Quiz_{}_Results.csv".format(quiz_Id)})
# Route to view the Analysis
@app.route("/viewAnalysis", methods=["GET", "POST"])
def viewAnalysis():
global teacher_Id, quiz_Id, teacherName
if request.method == "GET":
# Checking for a stable connection and connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185, user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return render_template("viewAnalysis.html", noNetwork=True, username=teacherName)
cur = conn.cursor()
# Fetching all Quiz id's of that user from Database
cur.execute('''SELECT QUIZ_ID FROM QUIZ WHERE TEACHER='{}' '''.format(teacher_Id))
data = cur.fetchall()
print(data)
# Committing and Closing the Database Connection
conn.commit()
conn.close()
return render_template("viewAnalysis.html", data=data, username=teacherName)
else:
# Getting the Quiz id entered by the user
quizId = request.form.get("QuizId")
quiz_Id = quizId
# Checking for a stable connection and connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return redirect("/teacherHome")
cur = conn.cursor()
# Fetching the no of students invited for the exam from Database
cur.execute('''SELECT COUNT(*) FROM STUDENT WHERE QUIZ_ID='{}' '''.format(quizId))
conn.commit()
noOfStudentsInvited = cur.fetchall()[0][0]
noOfStudentsAttempted = noOfStudentsSkipped = avgMark = aboveAvg = belowAvg = 0
if noOfStudentsInvited != '0':
# Fetching Students who have attempted the Exam
cur.execute('''SELECT COUNT(*) FROM STUDENT WHERE QUIZ_ID='{}' AND MARKS != '{}' '''.format(quizId, None))
conn.commit()
noOfStudentsAttempted = cur.fetchall()[0][0]
# SkippedStudents will be with marks None
noOfStudentsSkipped = int(noOfStudentsInvited) - int(noOfStudentsAttempted)
# Fetching the Avg marks of the Students
cur.execute('''SELECT AVG(MARKS) FROM STUDENT WHERE QUIZ_ID='{}' AND MARKS != '{}' '''.format(quizId, None))
conn.commit()
avgMark = cur.fetchall()[0][0]
# Selecting the no of students with marks above Average
cur.execute(
'''SELECT COUNT(*) FROM STUDENT WHERE QUIZ_ID='{}' AND MARKS >= '{}' AND MARKS !='None' '''.format(
quizId, avgMark))
conn.commit()
aboveAvg = cur.fetchall()[0][0]
belowAvg = int(noOfStudentsAttempted) - int(aboveAvg)
return render_template("overallAnalysis.html", noOfStudentsInvited=noOfStudentsInvited,
noOfStudentsAttempted=noOfStudentsAttempted, noOfStudentsSkipped=noOfStudentsSkipped,
avgMark=avgMark, aboveAvg=aboveAvg, belowAvg=belowAvg)
# Route To View Detailed Analysis
@app.route("/detailedAnalysis", methods=["GET", "POST"])
def detailedAnalysis():
global quiz_Id, totalQuestions
# Checking for a stable connection and connecting to the Database
try:
conn = pymysql.connect(host="mysql-29185-0.cloudclusters.net", port=29185,
user="DARKKNIGHT",
passwd=PASSWORD, database="DBMSFLASKPROJECT")
except Exception as E:
print(E)
return redirect("/teacherHome")
cur = conn.cursor()
slices = []
sl = []
# Selecting no of questions of that quiz from the database
cur.execute('''SELECT NO_OF_QUESTIONS FROM QUIZ WHERE QUIZ_ID='{}' '''.format(quiz_Id))
totQuestions = cur.fetchall()[0][0]
totalQuestions = totQuestions
# Selecting Students who answered question with option 1, option 2, option 3, option 4 for every question with quiz
for q in range(0, totQuestions):