forked from Lunatic-Labs/rubricapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
2305 lines (2036 loc) · 105 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
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
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask import Flask, render_template, redirect, url_for, request, send_file, jsonify
from flask_wtf.file import FileField, FileAllowed, FileRequired
from flask_sqlalchemy import SQLAlchemy
from filelock import Timeout, FileLock
from flask_bootstrap import Bootstrap
from fpdf import FPDF, HTMLMixin
from flask_wtf import FlaskForm
from werkzeug.security import generate_password_hash, check_password_hash
from wtforms import StringField, PasswordField, BooleanField
import wtforms.validators as validators
from django.utils.safestring import mark_safe
from django.template import Library
from concurrent.futures import ThreadPoolExecutor, as_completed
from email.message import EmailMessage
from openpyxl import load_workbook
from xml.dom import ValidationErr
import subprocess
import platform
import datetime
import openpyxl
import smtplib
# shutil used to delete whole directory(folder)
import shutil
import uuid
import json
import time
import json
import sys
import os
# from classes import LoginForm, RegisterForm
register = Library()
# file directory
# requirement of two arguments: file address of app.py and fire address of root directory.
files_dir = None
if len(sys.argv) > 1:
files_dir = sys.argv[1]
elif platform.node() in ['rubric.cs.uiowa.edu', 'rubric-dev.cs.uiowa.edu']:
files_dir = "/var/www/wsgi-scripts/rubric"
else:
print(
"Requires argument: path to put files and database (suggestion is `pwd` when already in directory containing app.py)")
sys.exit(1)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisissupposedtobesecret!'
if platform.node() in ['rubric.cs.uiowa.edu', 'rubric-dev.cs.uiowa.edu']:
dbpass = None
with open("{}/dbpass".format(files_dir), 'r') as f:
dbpass = f.readline().rstrip()
dbuser = None
with open("{}/dbuser".format(files_dir), 'r') as f:
dbuser = f.readline().rstrip()
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{0}:{1}@127.0.0.1/rubric'.format(
dbuser, dbpass)
else:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}/account.db'.format(
files_dir)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# tables in database; each class match to a table in database
# *size of username, project_id, owner, project_name should be consistent in different tables.
# *password is encrypted
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
# use username or email to login
username = db.Column(db.String(30), unique=True, nullable=False)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(80), nullable=False)
#role in university; ex. instructor or ta
role = db.Column(db.String(20), nullable=True)
University = db.Column(db.String(255), nullable=True)
# self introduction
description = db.Column(db.String(255), nullable=True)
class Permission(UserMixin, db.Model):
# project_id is made up with projectname, owner, shareto
project_id = db.Column(db.String(255), primary_key=True)
owner = db.Column(db.String(30), nullable=False)
shareTo = db.Column(db.String(30), nullable=False)
# project is project name
project = db.Column(db.String(150), nullable=False)
status = db.Column(db.String(50), nullable=False)
class Project(UserMixin, db.Model):
project_name = db.Column(db.String(150), primary_key=True)
owner = db.Column(db.String(30), primary_key=True)
project_status = db.Column(db.String(50), nullable=False)
description = db.Column(db.String(255), nullable=True)
class Evaluation(UserMixin, db.Model):
# sharer of project can also create evaluation (or not allowed); still undecided
eva_name = db.Column(db.String(150), primary_key=True)
project_name = db.Column(db.String(150), primary_key=True)
project_owner = db.Column(db.String(30), primary_key=True)
owner = db.Column(db.String(30), nullable=False)
description = db.Column(db.String(255), nullable=True)
last_edit = db.Column(db.String(30), nullable=True)
# not using this table right now
# designed to send messages among users
class Notification(UserMixin, db.Model):
notification_id = db.Column(db.Integer, primary_key=True)
from_user = db.Column(db.String(30), nullable=False)
to_user = db.Column(db.String(50), nullable=False)
message_type = db.Column(db.String(50), nullable=False)
message_content = db.Column(db.String(255), nullable=True)
status = db.Column(db.String(50), nullable=False)
time = db.Column(db.String(50), nullable=False)
appendix = db.Column(db.String(255), nullable=True)
# besides uploading rubric, we also offer default rubric
class DefaultRubric(UserMixin, db.Model):
json_name = db.Column(db.String(150), primary_key=True)
json_description = db.Column(db.String(500), nullable=True)
json_owner = db.Column(db.String(30), nullable=True)
# sending emails usually takes a long time; this table record information of the process of email sending
class EmailSendingRecord(UserMixin, db.Model):
project_name = db.Column(db.String(150), primary_key=True)
project_owner = db.Column(db.String(30), primary_key=True)
eva_name = db.Column(db.String(150), primary_key=True)
num_of_tasks = db.Column(db.Integer, nullable=True)
num_of_finished_tasks = db.Column(db.Integer, nullable=True)
# Settings of Directory ======================================================================================================
# SET THE BASE DIRECTORY
os.chdir(files_dir)
base_directory = os.getcwd()
home_directory = base_directory
base_directory = base_directory + "/users"
# login manager is a extension library for login system including login_required
# login_required
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class LoginForm(FlaskForm):
email = StringField('Email', validators=[validators.InputRequired(
), validators.Email(message='Invalid email'), validators.Length(max=255)])
password = PasswordField('Password', validators=[
validators.InputRequired(), validators.Length(min=8, max=80)])
remember = BooleanField('Remember me')
class RegisterForm(FlaskForm):
email = StringField('Email', validators=[validators.InputRequired(
), validators.Email(message='Invalid email'), validators.Length(max=255)])
password = PasswordField('Password', validators=[validators.InputRequired(), validators.Length(
min=8, max=80), validators.EqualTo('checkpassword', message='Passwords must match')], description="password size between 8-80")
checkpassword = PasswordField('Check Password', validators=[validators.InputRequired(
), validators.Length(min=8, max=80)], description="write password again")
@register.filter(is_safe=True)
def js(obj):
return mark_safe(json.dumps(obj))
# Validator is function which checks whether the information is correct before proceed;
# NameValidator is used in login
class NameValidator(object):
@login_required
def __call__(self, form, field):
duplicate_project_name = Project.query.filter_by(project_name=field.data,
owner=current_user.username).first()
# print(field.data)
# print(current_user.username)
# print(duplicate_project_name)
if duplicate_project_name is not None:
raise ValidationErr("The project name has been used before")
# check whether primary keys are in the student file;
class validate_project_student_file(object):
@login_required
def __call__(self, form, field):
try:
path_to_current_user = "{}/{}".format(
base_directory, current_user.username)
path_to_student_file_stored = "{}/".format(path_to_current_user)
student_file_filename = "student.xlsx"
field.data.save(path_to_student_file_stored +
student_file_filename)
student_file_workbook = load_workbook(
path_to_student_file_stored + student_file_filename)
student_file_worksheet = student_file_workbook['Sheet1']
find_Student = True if 'Student' in [x.value for x in
list(student_file_worksheet.iter_rows())[0]] else False
find_Email = True if 'Email' in [x.value for x in list(
student_file_worksheet.iter_rows())[0]] else False
find_group = True if 'group' in [x.value for x in list(
student_file_worksheet.iter_rows())[0]] else False
find_meta_group = True if 'meta' in [x.value for x in list(
student_file_worksheet.iter_rows())[0]] else False
if find_group is False:
# os.remove(path_to_student_file_stored)
raise ValidationErr("Can not find group")
elif find_Student is False:
raise ValidationErr("Can not find Student")
elif find_Email is False:
raise ValidationErr("Can not find Email")
# os.remove(path_to_student_file_stored+student_file_filename)
elif find_meta_group is False:
raise ValidationErr("Can not find meta - group")
except Exception as e:
raise ValidationErr(e)
# check whether primary keys are in the rubric json file
class validate_project_json_file(object):
@login_required
def __call__(self, form, field):
try:
path_to_current_user = "{}/{}".format(
base_directory, current_user.username)
path_to_json_file_stored = "{}/".format(path_to_current_user)
json_file_filename = "TW.json"
field.data.save(path_to_json_file_stored + json_file_filename)
myLock = FileLock((path_to_json_file_stored +
json_file_filename) + '.lock', timeout=5)
with myLock:
with open(path_to_json_file_stored + json_file_filename, 'r')as f:
json_data = json.loads(f.read(), strict=False)
if 'name' in json_data.keys() and 'category' in json_data.keys():
for category in json_data['category']:
if 'name' in category.keys() and 'section' in category.keys():
category_name = (category['name'])
for section in category['section']:
if 'name' in section.keys() and 'type' in section.keys() and 'values' in section.keys():
for value in section['values']:
if 'name' not in value.keys() or 'desc' not in value.keys():
raise ValidationErr(
"lack of NAME or DESC in json file")
else:
raise ValidationErr(
"lack of NAME or TYPE or VALUES in json file")
else:
raise ValidationErr(
"lack of NAME or SECTIONS in json file")
else:
raise ValidationErr("lack of NAME or CATEGORY in json file")
except Exception as e:
raise ValidationErr(e)
# os.remove(path_to_json_file_stored+ json_file_filename)
# flaskform for wtf
class ProjectForm(FlaskForm):
project_name = StringField('Project Name',
validators=[validators.InputRequired(), validators.Length(min=3, max=150), NameValidator()], description="3-150 characters")
project_description = StringField('Description', validators=[
validators.Length(min=0, max=255)], description="0-255 characters")
student_file = FileField('Roster', validators=[
validators.InputRequired(), validate_project_student_file()])
json_file = FileField('Rubric', validators=[
validators.InputRequired(), validate_project_json_file()])
# messages for the project_profile page
class ManageProjectMessage:
def __init__(self, path, message, type):
self.path = path
self.message = message
self.type = type
class ManageProjectMessages:
UserNotFound = ManageProjectMessage("unf", "User not found", "negative")
Created = ManageProjectMessage(
"create", "Permission successfully created", "positive")
NotYourself = ManageProjectMessage(
"self", "You cannot give permission to yourself", "negative")
Failed = ManageProjectMessage(
"fail", "Failed to create permission for unknown reason", "negative")
NoMessage = ManageProjectMessage("success", "", "none")
UpdatedAuthority = ManageProjectMessage(
"upauth", "successfully updated authority", "positive")
DeletedPerm = ManageProjectMessage(
"delperm", "successfully delete permission", "positive")
FailedUpAuth = ManageProjectMessage(
"failupauth", "failure to update authority", "negative")
@classmethod
def lookup(cls, msg):
return {cls.UserNotFound.path: cls.UserNotFound,
cls.Created.path: cls.Created,
cls.NotYourself.path: cls.NotYourself,
cls.Failed.path: cls.Failed,
cls.NoMessage.path: cls.NoMessage,
cls.UpdatedAuthority.path: cls.UpdatedAuthority,
cls.DeletedPerm.path: cls.DeletedPerm,
cls.FailedUpAuth.path: cls.FailedUpAuth}[msg]
@app.route('/')
def index():
return render_template('index.html')
# log in function; Access User table
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
# login validator
if form.validate_on_submit():
user = User.query.filter_by(username=form.email.data).first()
if user:
if check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
# instructor jump to instructor page, student jump to student page
# if(user.instructor == "1"):
# jacky: after login, users are directed to the Rubric page, instead of Overview page
return redirect(url_for('instructor_project'))
else:
return render_template('login.html', msg="password not correct", form=form)
else:
return render_template('login.html', msg="user doesn't exist", form=form)
return render_template('login.html', msg="", form=form)
# sign up function; Access User table
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = RegisterForm()
# signup validator
if form.validate_on_submit():
# check if the user and email has existed in the database
email_is_taken = User.query.filter_by(email=form.email.data).first()
if email_is_taken:
return render_template('signup.html', form=form, msg="That email address is already associated with an account")
else:
hashed_password = generate_password_hash(
form.password.data, method='sha256')
# In issue 28, we changed username to be email, we saved the username section as we don't need to change the table
new_user = User(username=form.email.data,
email=form.email.data, password=hashed_password)
db.session.add(new_user)
db.session.commit()
# After making sure that the new user is created, the user's private folder can be created by using the user name
path_to_user_folder = "{}/{}".format(
base_directory, new_user.username)
os.mkdir(path_to_user_folder)
return redirect(url_for('login'))
return render_template('signup.html', form=form, msg="")
# home page
@app.route('/instructor_dashboard')
@login_required
def instructor_dashboard():
# Load all projects to instructor_dashboard
# Find all projects in User's private folder by using current user
path_to_current_user = "{}/{}".format(base_directory,
current_user.username)
project_list = [x.project for x in Permission.query.filter_by(
owner=current_user.username, shareTo=current_user.username).all()]
project_len = len(project_list)
return render_template('instructor_dashboard.html', name=current_user.username, project_list=project_list,
project_len=project_len)
# Manage Rubrics: showing all private rubric;
@app.route('/project_profile_jumptool', methods=["POST", "GET"])
@login_required
def project_profile_jumptool():
# a jump tool before load project
# display the information of projects (title and desc) and its recent evaluations
path_to_current_user = "{}/{}".format(base_directory,
current_user.username)
# list of evaluation & list of groups relating to one project
project_set_map = {}
# search projects in database by username
project_list = Permission.query.filter_by(
owner=current_user.username, shareTo=current_user.username).all()
project_information_map = {}
for project in project_list:
path_to_evaluation_file = "{}/{}/{}/evaluation.xlsx".format(base_directory, current_user.username,
project.project)
evaluation_workbook = openpyxl.load_workbook(path_to_evaluation_file)
evaluation_worksheet = evaluation_workbook['eva']
group_worksheet = evaluation_workbook['group']
group_col = []
for col_item in list(group_worksheet.iter_cols())[0]:
if col_item.value != "groupid":
group_col.append(col_item.value)
set_of_eva = Evaluation.query.filter_by(
project_name=project.project, project_owner=current_user.username).all()
project_set_map[project.project] = (group_col, set_of_eva)
project_information_map[project.project] = Project.query.filter_by(project_name=project.project,
owner=project.owner).first()
return render_template("project_profile_jumptool.html", project_list=project_list, project_set_map=project_set_map,
project_information_map=project_information_map)
# Manage Rubrics: show single rubric and its evaluation grading status(graded group, ungraded group, grade table, )
@app.route('/project_profile/<string:project_id>/<string:msg>', methods=["POST", "GET"])
@login_required
def project_profile(project_id, msg):
"""
It controls the project_profile.html page, it collects a list of all the evaluations and get them displayed on the web
page
:param project_id: project id
:param msg: it is used to make sure the page is correctly loaded, if not, the error message will be displayed in the
error box in the web page
:return: a rendered web page with dictionaries map the info of current project
"""
# show each grade in this project and divided into eva s
project = Permission.query.filter_by(project_id=project_id).first()
list_of_shareTo_permission = [x for x in
Permission.query.filter_by(
project=project.project, owner=current_user.username).all()
if x.shareTo != current_user.username]
path_to_evaluation_file = "{}/{}/{}/evaluation.xlsx".format(
base_directory, current_user.username, project.project)
evaluation_workbook = openpyxl.load_workbook(path_to_evaluation_file)
evaluation_worksheet = evaluation_workbook['eva']
group_worksheet = evaluation_workbook['group']
meta_worksheet = evaluation_workbook['meta']
list_of_eva = select_by_col_name('eva_name', evaluation_worksheet)
set_of_eva = set(list_of_eva)
# get all groups and its owners
dic_of_eva = {}
dic_of_choosen = {}
set_of_meta = set(select_by_col_name('metaid', meta_worksheet))
meta_group_map_list = []
for group_index in range(2, len(list(meta_worksheet.iter_rows())) + 1):
meta_group_map_list.append(
select_map_by_index(group_index, meta_worksheet))
for eva in set_of_eva:
all_groups_choosen = set()
all_groups_not_choosen = set()
all_groups = set()
choosen = {}
for meta in set_of_meta:
choosen[meta] = set()
total = {}
notchoosen = {}
for meta in set_of_meta:
notchoosen[meta] = set(
[x['groupid'] for x in meta_group_map_list if str(x['metaid']) == str(meta)])
total[meta] = set(
[x['groupid'] for x in meta_group_map_list if str(x['metaid']) == str(meta)])
# update 9/13: simple profile
dic_of_eva[eva] = []
temp_eva = select_row_by_group_id(
"eva_name", eva, evaluation_worksheet)
for eva_row in temp_eva:
dic_of_eva[eva].append(eva_row)
for (key, value) in eva_row.items():
if (key != "group_id") and (key != "eva_name") and (key != "owner") and (key != "date") and (key != "students") and (key != "last_updates"):
if (value is not None) and (value != " ") and (value != ""):
metaid = [x[0] for x in list(
total.items()) if eva_row["group_id"] in x[1]][0]
choosen[metaid].add(eva_row["group_id"])
notchoosen[metaid].discard(eva_row["group_id"])
for meta in set_of_meta:
for choosen_i in choosen[meta]:
all_groups_choosen.add(choosen_i)
for notchoosen_j in notchoosen[meta]:
all_groups_not_choosen.add(notchoosen_j)
for all_k in total[meta]:
all_groups.add(all_k)
dic_of_choosen[eva] = (choosen, notchoosen, total,
all_groups_choosen, all_groups_not_choosen, all_groups)
tags = [x.value for x in list(evaluation_worksheet.iter_rows())[0]]
# group management
management_groups = []
rows_got_from_group_worksheet = list(group_worksheet.iter_rows())
for row in rows_got_from_group_worksheet:
management_groups.append([x.value for x in row])
records = EmailSendingRecord.query.filter_by(
project_name=project.project, project_owner=current_user.username).all()
if records is not None:
sending_info_dict = {}
for record in records:
sending_info_dict[record.eva_name] = [
record.num_of_tasks, record.num_of_finished_tasks]
print(sending_info_dict)
else:
sending_info_dict = {}
permission_message = ManageProjectMessages.lookup(msg)
return render_template("project_profile.html", dic_of_eva=dic_of_eva, meta_list=set_of_meta,
list_of_shareTo_permission=list_of_shareTo_permission, management_groups=management_groups,
tags=tags, project=project, set_of_eva=list(set_of_eva), dic_of_choosen=dic_of_choosen,
msg=permission_message.message, msg_type=permission_message.type,
sending_info_dict=sending_info_dict)
@app.route('/management_group/<string:project_id>', methods=['GET', 'POST'])
@login_required
def managment_group(project_id):
project = Permission.query.filter_by(project_id=project_id).first()
path_to_evaluation_xlsx = "{}/{}/{}/evaluation.xlsx".format(
base_directory, current_user.username, project.project)
evaluation_workbook = openpyxl.load_workbook(path_to_evaluation_xlsx)
group_worksheet = evaluation_workbook['group']
for row_index in range(1, len(list(group_worksheet.iter_rows()))):
for col_index in range(1, len(list(group_worksheet.iter_cols()))):
student_email = request.form.get((list(group_worksheet.iter_cols())[0][row_index].value + str(col_index)),
" ")
# group management detector
# if the given value is None, inserted should also be None
if student_email == " " or student_email == "None":
group_worksheet.cell(row_index + 1, col_index + 1).value = None
else:
group_worksheet.cell(
row_index + 1, col_index + 1).value = student_email
evaluation_workbook.save(path_to_evaluation_xlsx)
return redirect(url_for("project_profile", project_id=project_id, msg=ManageProjectMessages.NoMessage.path))
@app.route('/delete_eva/<string:project_id>/<string:evaluation>/<string:group>/<string:grader>/<string:datetime>',
methods=['GET', 'POST'])
@login_required
def delete_eva(project_id, evaluation, group, grader, datetime):
project = Permission.query.filter_by(project_id=project_id).first()
path_to_evaluation_xlsx = "{}/{}/{}/evaluation.xlsx".format(
base_directory, current_user.username, project.project)
evaluation_workbook = openpyxl.load_workbook(path_to_evaluation_xlsx)
evaluation_worksheet = evaluation_workbook['eva']
group_worksheet = evaluation_workbook['group']
allgroups = select_by_col_name('groupid', group_worksheet)
students_worksheet = evaluation_workbook['students']
index = int(select_index_by_group_eva_owner_date(
evaluation, group, grader, datetime, evaluation_worksheet))
evaluation_worksheet.delete_rows(index, 1)
# check whether all group have at least one empty grade in this evaluation
group_col_in_eva = set(select_by_col_name('group', evaluation_worksheet))
empty_group = [x for x in allgroups if x not in group_col_in_eva]
students = get_students_by_group(group_worksheet, students_worksheet)
for empty in empty_group:
students_name = []
# couple is [email, student_name]
for student_couple in students[str(group)]:
students_name.append(student_couple[1])
empty_row = new_row_generator(
str(group), students_name, evaluation, evaluation_worksheet)
evaluation_worksheet.append(empty_row)
evaluation_workbook.save(path_to_evaluation_xlsx)
return redirect(url_for("project_profile", project_id=project_id, msg=ManageProjectMessages.NoMessage.path))
@app.route('/delete_project/<string:project_id>', methods=['GET', 'POST'])
@login_required
def delete_project(project_id):
"""
Delete a project from database
:param project_id: project id
:return: rerender current page
"""
project = Permission.query.filter_by(project_id=project_id).first()
permission_to_delete = Permission.query.filter_by(
project=project.project).all()
path_to_current_project = "{}/{}/{}".format(
base_directory, current_user.username, project.project)
if os.path.exists(path_to_current_project):
shutil.rmtree(path_to_current_project)
# after delete the folder, delete all the permissions that were send from the project
for permission in permission_to_delete:
db.session.delete(permission)
db.session.commit()
# delete the project in project table
project_in_database = Project.query.filter_by(
project_name=project.project, owner=project.owner).first()
db.session.delete(project_in_database)
db.session.commit()
# FIXME: these messages are not being used
msg = "project deleted"
else:
msg = "the project to be deleted could not be found"
return redirect(url_for("project_profile_jumptool", project_id=project_id))
@app.route('/update_permission/<string:project_id>/<string:project_id_full>', methods=["GET", "POST"])
@login_required
def update_permission(project_id, project_id_full):
try:
submit = request.form['submit']
if submit == 'update':
authority = request.form['authority']
query = Permission.query.filter_by(project_id=project_id).first()
query.status = authority
db.session.commit()
msg = ManageProjectMessages.UpdatedAuthority.path
else:
query = Permission.query.filter_by(project_id=project_id).first()
db.session.delete(query)
db.session.commit()
msg = ManageProjectMessages.DeletedPerm.path
except Exception as e:
msg = ManageProjectMessages.FailedUpAuth.path
return redirect(url_for("project_profile", project_id=project_id_full, msg=msg))
@app.route('/create_permission/<string:project_id>', methods=["GET", "POST"])
@login_required
def create_permission(project_id):
"""
This is being used in project_profile.html, which creates permission to a another user to share the rubric. The func-
ction first search the typed in username, if the user exist, it creates a permission in Permission table, otherwise
it returns to current page with error messages displayed
:param project_id: current project id
:return: It depends on the validity of typed in username
"""
try:
username = request.form.get('username', " ")
authority = "overwrite"
pending_authority = "pending|{}".format(authority)
account_user = User.query.filter_by(username=username).first()
if username != current_user.username:
if account_user is not None:
# create permission:
project = Permission.query.filter_by(
project_id=project_id).first()
permission_projectid = "{}{}{}{}".format(
current_user.username, username, project.project, authority)
permission_existed = Permission.query.filter_by(
project_id=permission_projectid).first()
if permission_existed:
return redirect(url_for("project_profile", project_id=project_id, msg="Permission existed!"))
else:
new_permission = Permission(project_id=permission_projectid, owner=current_user.username, shareTo=username,
project=project.project, status=pending_authority)
db.session.add(new_permission)
db.session.commit()
return redirect(url_for("project_profile", project_id=project_id, msg=ManageProjectMessages.Created.path))
else:
return redirect(url_for("project_profile", project_id=project_id, msg=ManageProjectMessages.UserNotFound.path))
else:
return redirect(url_for("project_profile", project_id=project_id, msg=ManageProjectMessages.NotYourself.path))
except:
return redirect(url_for("project_profile", project_id=project_id, msg=ManageProjectMessages.Failed.path))
@app.route('/instructor_project', methods=["POST", "GET"])
@login_required
def instructor_project():
"""
Load All project and shared project from database for the current user
:return: a rendered template with all the projects the current user has
"""
list_of_all_projects = Permission.query.filter_by(
shareTo=current_user.username).all()
list_of_personal_projects = Permission.query.filter_by(owner=current_user.username,
shareTo=current_user.username).all()
list_of_shared_project = []
for project in list_of_all_projects:
flag = True
for personal_project in list_of_personal_projects:
if project.project_id == personal_project.project_id:
flag = False
if flag:
list_of_shared_project.append(project)
list_of_personal_project_database = {}
list_of_shared_project_database = {}
# load the description of project
for personal_project in list_of_personal_projects:
project_in_project_db = Project.query.filter_by(project_name=personal_project.project,
owner=personal_project.owner).first()
list_of_personal_project_database[project_in_project_db.project_name] = project_in_project_db
for shared_project in list_of_shared_project:
project_in_project_db = Project.query.filter_by(project_name=shared_project.project,
owner=shared_project.owner).first()
list_of_shared_project_database[project_in_project_db.project_name] = project_in_project_db
return render_template('instructor_project.html', personal_project_list=list_of_personal_projects,
shared_project_list=list_of_shared_project,
list_of_personal_project_database=list_of_personal_project_database,
list_of_shared_project_database=list_of_shared_project_database)
@app.route('/create_project', methods=["POST", "GET"])
@login_required
def create_project():
"""
# Request from file by WTF
# Create a new project folder under 'path_to_current_user'
# save files in new folder and build a evaluation doc depending on json file
:return:
"""
path_to_current_user = "{}/{}".format(base_directory,
current_user.username)
path_to_student_file = "{}/student.xlsx".format(path_to_current_user)
path_to_json_file = "{}/TW.json".format(path_to_current_user)
form = ProjectForm()
try:
if form.validate_on_submit():
# create project folder
path_to_current_user_project = "{}/{}/{}".format(
base_directory, current_user.username, form.project_name.data)
os.mkdir(path_to_current_user_project)
path_to_student_file_stored = "{}/student.xlsx".format(
path_to_current_user_project)
shutil.move(path_to_student_file, path_to_student_file_stored)
path_to_json_file_stored = "{}/TW.json".format(
path_to_current_user_project)
shutil.move(path_to_json_file, path_to_json_file_stored)
# creating evaluation doc based on grading criteria json file
# copy student sheet to evaluation doc
student_file_workbook = openpyxl.load_workbook(
path_to_student_file_stored)
student_file_worksheet = student_file_workbook['Sheet1']
# create group file depending on student file
list_of_group = select_by_col_name('group', student_file_worksheet)
set_of_group = set(list_of_group)
# Fixing a bug where a None element was found. Is this safe?
set_of_group.discard(None)
# create a group workbook
path_to_group_file = "{}/group.xlsx".format(
path_to_current_user_project)
group_workbook = openpyxl.Workbook()
group_file_worksheet = group_workbook.create_sheet('Sheet1')
meta_file_worksheet = group_workbook.create_sheet('Sheet2')
# all student information map
student_map_list = []
for student_index in range(2, len(list(student_file_worksheet.iter_rows())) + 1):
student_map_list.append(select_map_by_index(
student_index, student_file_worksheet))
# insert group columns
group_file_worksheet.cell(1, 1).value = 'groupid'
meta_file_worksheet.cell(1, 1).value = 'groupid'
meta_file_worksheet.cell(1, 2).value = 'metaid'
start_index = 2
max_num_students_pergroup = 0
for group in set_of_group:
group_file_worksheet.cell(start_index, 1).value = group
student_emails = [x['Email']
for x in student_map_list if x['group'] == group]
if len(student_emails) > max_num_students_pergroup:
max_num_students_pergroup = len(student_emails)
meta_file_worksheet.cell(start_index, 1).value = group
meta_group = [x['meta']
for x in student_map_list if x['group'] == group][0]
meta_file_worksheet.cell(start_index, 2).value = meta_group
for insert_index in range(2, len(student_emails) + 2):
group_file_worksheet.cell(
start_index, insert_index).value = student_emails[insert_index - 2]
start_index += 1
for index in range(1, max_num_students_pergroup+1):
group_file_worksheet.cell(
1, 1+index).value = ("student" + str(index))
group_workbook.save(path_to_group_file)
path_to_evaluation = "{}/evaluation.xlsx".format(
path_to_current_user_project)
evaluation_workbook = openpyxl.Workbook()
evaluation_group = evaluation_workbook.create_sheet('group')
evaluation_meta = evaluation_workbook.create_sheet('meta')
evaluation_student = evaluation_workbook.create_sheet('students')
copy_all_worksheet(evaluation_group, group_file_worksheet)
copy_all_worksheet(evaluation_meta, meta_file_worksheet)
copy_all_worksheet(evaluation_student, student_file_worksheet)
# create EVA depending on the json file
evaluation_eva = evaluation_workbook.create_sheet('eva')
# open json file and load json
myLock = FileLock(path_to_json_file_stored+'.lock', timeout=5)
with myLock:
with open(path_to_json_file_stored, 'r')as f:
json_data = json.loads(f.read(), strict=False)
# The group id, eva_name, date are defults
tags_to_append = ['group_id', 'eva_name',
'owner', 'date', 'students']
for category in json_data['category']:
category_name = (category['name'])
for section in category['section']:
# instructors don't care about the text value, the text values will only be send to students.
if section['type'] != 'text':
value_to_append = "{}|{}".format(
category_name, section['name'])
tags_to_append.append(value_to_append)
tags_to_append.append("comment")
tags_to_append.append("last_updates")
evaluation_eva.append(tags_to_append)
evaluation_workbook.save(path_to_evaluation)
# create permission to owener himself
project_id = "{}{}{}{}".format(
current_user.username, current_user.username, form.project_name.data, 'full')
self_permission = Permission(project_id=project_id, owner=current_user.username, shareTo=current_user.username,
project=form.project_name.data, status='full')
db.session.add(self_permission)
db.session.commit()
# create the project in database
project_to_add = Project(project_name=form.project_name.data, project_status='public',
owner=current_user.username, description=form.project_description.data)
db.session.add(project_to_add)
db.session.commit()
return redirect(url_for("instructor_project"))
else:
if os.path.exists(path_to_student_file):
os.remove(path_to_student_file)
if os.path.exists(path_to_json_file):
os.remove(path_to_json_file)
return render_template('create_project.html', form=form, alert="")
except Exception as e:
if os.path.exists(path_to_student_file):
os.remove(path_to_student_file)
if os.path.exists(path_to_json_file):
os.remove(path_to_json_file)
return render_template("create_project.html", form=form, alert=e)
def copy_all_worksheet(copy_to, copy_from):
for row in range(0, len(list(copy_from.iter_rows()))):
for col in range(0, len(list(copy_from.iter_cols()))):
copy_to.cell(row=row + 1, column=col +
1).value = copy_from.cell(row=row + 1, column=col + 1).value
@app.route('/create_project_by_share/<string:project_id>', methods=["POST", "GET"])
@login_required
def create_project_by_share(project_id):
"""
:param project_id:
:return:
"""
new_project_name = request.form['project_name']
duplicate_project_name = Project.query.filter_by(
project_name=new_project_name, owner=current_user.username).first()
if duplicate_project_name is not None:
return redirect(url_for('account', msg="This rubric name has been used before"))
path_to_current_user_project = "{}/{}/{}".format(
base_directory, current_user.username, new_project_name)
# copy json file:
project = Permission.query.filter_by(project_id=project_id).first()
if project is not None:
owner = project.owner
project_name = project.project
# use project name and project owner info to locate the path of json
path_to_json_file = "{}/{}/{}/TW.json".format(
base_directory, owner, project_name)
path_to_json_file_stored = "{}/TW.json".format(
path_to_current_user_project)
if os.path.exists(path_to_json_file):
os.mkdir(path_to_current_user_project)
shutil.copy2(path_to_json_file, path_to_json_file_stored)
else:
return redirect('account', msg="the rubric you were trying to copy has been deleted")
else:
return redirect('account', msg="the rubric you were trying to copy has been deleted")
new_project_desc = request.form['project_desc']
student_file = request.files['student_file']
path_to_student_file_stored = "{}/student.xlsx".format(
path_to_current_user_project)
student_file.save(path_to_student_file_stored)
# check if the student file is valid:
student_file_workbook = load_workbook(path_to_student_file_stored)
student_file_worksheet = student_file_workbook['Sheet1']
find_Student = True if 'Student' in [x.value for x in list(
student_file_worksheet.iter_rows())[0]] else False
find_Email = True if 'Email' in [x.value for x in list(
student_file_worksheet.iter_rows())[0]] else False
find_group = True if 'group' in [x.value for x in list(
student_file_worksheet.iter_rows())[0]] else False
find_meta_group = True if 'meta' in [x.value for x in list(
student_file_worksheet.iter_rows())[0]] else False
if find_Student is False:
return redirect('account', msg="no Student column in student file!")
if find_Email is False:
return redirect('account', msg="no Email column in student file!")
if find_group is False:
return redirect('account', msg="no group column in student file!")
if find_meta_group is False:
return redirect('account', msg="no meta group column in student file!")
# create project:
# create group file depending on student file
list_of_group = select_by_col_name('group', student_file_worksheet)
set_of_group = set(list_of_group)
# Fixing a bug where a None element was found. Is this safe?
set_of_group.discard(None)
# create a group workbook
path_to_group_file = "{}/group.xlsx".format(path_to_current_user_project)
group_workbook = openpyxl.Workbook()
group_file_worksheet = group_workbook.create_sheet('Sheet1')
meta_file_worksheet = group_workbook.create_sheet('Sheet2')
# all student information map
student_map_list = []
for student_index in range(2, len(list(student_file_worksheet.iter_rows())) + 1):
student_map_list.append(select_map_by_index(
student_index, student_file_worksheet))
# insert group columns
group_file_worksheet.cell(1, 1).value = 'groupid'
meta_file_worksheet.cell(1, 1).value = 'groupid'
meta_file_worksheet.cell(1, 2).value = 'metaid'
start_index = 2
for group in set_of_group:
group_file_worksheet.cell(start_index, 1).value = group
student_emails = [x['Email']
for x in student_map_list if x['group'] == group]
meta_file_worksheet.cell(start_index, 1).value = group
meta_group = [x['meta']
for x in student_map_list if x['group'] == group][0]
meta_file_worksheet.cell(start_index, 2).value = meta_group
for insert_index in range(2, len(student_emails) + 2):
group_file_worksheet.cell(
start_index, insert_index).value = student_emails[insert_index - 2]
start_index += 1
group_workbook.save(path_to_group_file)
path_to_evaluation = "{}/evaluation.xlsx".format(
path_to_current_user_project)
evaluation_workbook = openpyxl.Workbook()
evaluation_group = evaluation_workbook.create_sheet('group')
evaluation_meta = evaluation_workbook.create_sheet('meta')
evaluation_student = evaluation_workbook.create_sheet('students')
copy_all_worksheet(evaluation_group, group_file_worksheet)
copy_all_worksheet(evaluation_meta, meta_file_worksheet)
copy_all_worksheet(evaluation_student, student_file_worksheet)
# create EVA depending on the json file
evaluation_eva = evaluation_workbook.create_sheet('eva')
# open json file and load json