-
Notifications
You must be signed in to change notification settings - Fork 314
/
api.py
3326 lines (2679 loc) · 117 KB
/
api.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 __future__ import division
from . import utils
import datetime
import subprocess as sp
from sqlalchemy import (create_engine, ForeignKey, Column, String, Text,
DateTime, Interval, Float, Enum, UniqueConstraint,
Boolean, inspect)
from sqlalchemy.orm import (sessionmaker, scoped_session, relationship,
column_property)
from sqlalchemy.orm.exc import NoResultFound, FlushError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.exc import IntegrityError, StatementError
from sqlalchemy.sql import and_, or_
from sqlalchemy import select, func, exists, case, literal_column, union_all
from sqlalchemy.ext.declarative import declared_attr
from tornado.log import app_log
from uuid import uuid4
from .dbutil import _temp_alembic_ini
from typing import List, Any, Optional, Union
from .auth import Authenticator
Base = declarative_base()
def new_uuid() -> str:
return uuid4().hex
def get_alembic_version() -> str:
with _temp_alembic_ini('sqlite:////tmp/gradebook.db') as alembic_ini:
output = sp.check_output(['alembic', '-c', alembic_ini, 'heads'])
head = output.decode().split("\n")[0].split(" ")[0]
return head
class InvalidEntry(ValueError):
pass
class MissingEntry(ValueError):
pass
class Assignment(Base):
"""Database representation of the master/source version of an assignment."""
__tablename__ = "assignment"
#: Unique id of the assignment (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Unique human-readable name for the assignment, such as "Problem Set 1"
name = Column(String(128), unique=True, nullable=False)
#: (Optional) Duedate for the assignment in datetime format, with UTC timezone
duedate = Column(DateTime())
#: The course for this assignment
course_id = Column(String(128), ForeignKey('course.id'), nullable=False)
course = relationship("Course", back_populates="assignments")
#: A collection of notebooks contained in this assignment, represented
#: by :class:`~nbgrader.api.Notebook` objects
notebooks = relationship("Notebook", back_populates="assignment", order_by="Notebook.name")
#: A collection of submissions of this assignment, represented by
#: :class:`~nbgrader.api.SubmittedAssignment` objects.
submissions = relationship("SubmittedAssignment", back_populates="assignment")
#: The number of submissions of this assignment
num_submissions = None
#: Maximum score achievable on this assignment, automatically calculated
#: from the :attr:`~nbgrader.api.Notebook.max_score` of each notebook
max_score = None
#: Maximum coding score achievable on this assignment, automatically
#: calculated from the :attr:`~nbgrader.api.Notebook.max_code_score` of
#: each notebook
max_code_score = None
#: Maximum written score achievable on this assignment, automatically
#: calculated from the :attr:`~nbgrader.api.Notebook.max_written_score` of
#: each notebook
max_written_score = None
def __init__(self, name, duedate=None, course_id="default_course", **kwargs):
self.name = name
self.duedate = duedate
self.course_id = course_id
def to_dict(self):
"""Convert the assignment object to a JSON-friendly dictionary
representation.
"""
return {
"id": self.id,
"name": self.name,
"duedate": self.duedate.isoformat() if self.duedate is not None else None,
"num_submissions": self.num_submissions,
"max_score": self.max_score,
"max_code_score": self.max_code_score,
"max_written_score": self.max_written_score,
"max_task_score": self.max_written_score,
}
def __repr__(self):
return "Assignment<{}>".format(self.name)
class Notebook(Base):
"""Database representation of the master/source version of a notebook."""
__tablename__ = "notebook"
__table_args__ = (UniqueConstraint('name', 'assignment_id'),)
#: Unique id of the notebook (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Unique human-readable name for the notebook, such as "Problem 1". Note
#: the uniqueness is only constrained within assignments (e.g. it is ok for
#: two different assignments to both have notebooks called "Problem 1", but
#: the same assignment cannot have two notebooks with the same name).
name = Column(String(128), nullable=False)
#: The :class:`~nbgrader.api.Assignment` object that this notebook is a
#: part of
assignment = relationship("Assignment", back_populates="notebooks")
#: Unique id of :attr:`~nbgrader.api.Notebook.assignment`
assignment_id = Column(String(32), ForeignKey('assignment.id'))
#: The json string representation of the kernelspec for this notebook
kernelspec = Column(String(1024), nullable=True)
_base_cells = relationship("BaseCell", back_populates="notebook")
#: A collection of grade cells contained within this notebook, represented
#: by :class:`~nbgrader.api.GradeCell` objects
@property
def grade_cells(self):
return [x for x in self._base_cells if isinstance(x, GradeCell)]
#: A collection of solution cells contained within this notebook, represented
#: by :class:`~nbgrader.api.SolutionCell` objects
@property
def solution_cells(self):
return [x for x in self._base_cells if isinstance(x, SolutionCell)]
#: A collection of task cells contained within this notebook, represented
#: by :class:`~nbgrader.api.TaskCell` objects
@property
def task_cells(self):
return [x for x in self._base_cells if isinstance(x, TaskCell)]
#: A collection of source cells contained within this notebook, represented
#: by :class:`~nbgrader.api.SourceCell` objects
source_cells = relationship("SourceCell", back_populates="notebook")
#: A collection of submitted versions of this notebook, represented by
#: :class:`~nbgrader.api.SubmittedNotebook` objects
submissions = relationship("SubmittedNotebook", back_populates="notebook")
#: The number of submissions of this notebook
num_submissions = None
#: Maximum score achievable on this notebook, automatically calculated
#: from the :attr:`~nbgrader.api.GradeCell.max_score` of each grade cell
max_score = None
#: Maximum coding score achievable on this notebook, automatically
#: calculated from the :attr:`~nbgrader.api.GradeCell.max_score` and
#: :attr:`~nbgrader.api.GradeCell.cell_type` of each grade cell
max_code_score = None
#: Maximum written score achievable on this notebook, automatically
#: calculated from the :attr:`~nbgrader.api.GradeCell.max_score` and
#: :attr:`~nbgrader.api.GradeCell.cell_type` of each grade cell
max_written_score = None
#: Whether there are any submitted versions of this notebook that need to
#: be manually graded, automatically determined from the
#: :attr:`~nbgrader.api.SubmittedNotebook.needs_manual_grade` attribute of
#: each submitted notebook
needs_manual_grade = None
def to_dict(self):
"""Convert the notebook object to a JSON-friendly dictionary
representation.
"""
return {
"id": self.id,
"name": self.name,
"num_submissions": self.num_submissions,
"max_score": self.max_score,
"max_code_score": self.max_code_score,
"max_written_score": self.max_written_score,
"max_task_score": self.max_task_score,
"needs_manual_grade": self.needs_manual_grade
}
def __repr__(self):
return "Notebook<{}/{}>".format(self.assignment.name, self.name)
class BaseCell(Base):
"""Database representation of a cell. It is meant as a base class for cells where additional behavior is added through mixin classes."""
__tablename__ = "base_cell"
__table_args__ = (UniqueConstraint('name', 'notebook_id', 'type'),)
#: Unique id of the grade cell (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Unique human-readable name of the cell. This need only be unique
#: within the notebook, not across notebooks.
name = Column(String(128), nullable=False)
#: The notebook that this cell is contained within, represented by a
#: :class:`~nbgrader.api.Notebook` object
notebook = relationship("Notebook", back_populates="_base_cells")
#: Unique id of the :attr:`~nbgrader.api.BaseCell.notebook`
notebook_id = Column(String(32), ForeignKey('notebook.id'), nullable=False)
#: The assignment that this cell is contained within, represented by a
#: :class:`~nbgrader.api.Assignment` object
@property
def assignment(self):
return self.notebook.assignment
def __repr__(self):
return "BaseCell<{}/{}/{}>".format(
self.assignment.name, self.notebook.name, self.name)
type = Column(String(50))
#: A collection of grades associated with this cell,
#: represented by :class:`~nbgrader.api.Grade` objects
grades = relationship("Grade", back_populates="cell")
#: A collection of comments associated with this cell,
#: represented by :class:`~nbgrader.api.Comment` objects
comments = relationship("Comment", back_populates="cell")
__mapper_args__ = {
'polymorphic_identity': 'BaseCell',
'polymorphic_on': type
}
class GradedMixin():
"""Mixin class providing the reference to a grade and the data members relevant for graded cells."""
#: Maximum score that can be assigned to this grade cell
@declared_attr
def max_score(cls):
return Column(Float(), nullable=False)
#: The cell type, either "code" or "markdown"
@declared_attr
def cell_type(cls):
return Column(Enum("code", "markdown", name="grade_cell_type", validate_strings=True), nullable=False)
class GradeCell(BaseCell, GradedMixin):
"""Database representation of the master/source version of a grade cell."""
__tablename__ = "grade_cells"
#: Unique id of the cell (automatically generated from BaseCell)
id = Column(String(32), ForeignKey('base_cell.id'), primary_key=True)
comments = None
def to_dict(self):
"""Convert the grade cell object to a JSON-friendly dictionary
representation. Note that this includes keys for ``notebook`` and
``assignment`` which correspond to the names of the notebook and
assignment, not the objects themselves.
"""
return {
"id": self.id,
"name": self.name,
"max_score": self.max_score,
"cell_type": self.cell_type,
"notebook": self.notebook.name,
"assignment": self.assignment.name
}
def __repr__(self):
return "GradeCell<{}/{}/{}>".format(
self.assignment.name, self.notebook.name, self.name)
__mapper_args__ = {
'polymorphic_identity': 'GradeCell',
}
class SolutionCell(BaseCell):
__tablename__ = "solution_cells"
#: Unique id of the cell (automatically generated from BaseCell)
id = Column(String(32), ForeignKey('base_cell.id'), primary_key=True)
grades = None
def to_dict(self):
"""Convert the solution cell object to a JSON-friendly dictionary
representation. Note that this includes keys for ``notebook`` and
``assignment`` which correspond to the names of the notebook and
assignment, not the objects themselves.
"""
return {
"id": self.id,
"name": self.name,
"notebook": self.notebook.name,
"assignment": self.assignment.name
}
def __repr__(self):
return "SolutionCell<{}/{}/{}>".format(
self.assignment.name, self.notebook.name, self.name)
__mapper_args__ = {
'polymorphic_identity': 'SolutionCell',
}
class TaskCell(BaseCell, GradedMixin):
"""Database representation of a task cell."""
__tablename__ = "task_cells"
#: Unique id of the cell (automatically generated from BaseCell)
id = Column(String(32), ForeignKey('base_cell.id'), primary_key=True)
def to_dict(self):
"""Convert the task cell object to a JSON-friendly dictionary
representation. Note that this includes keys for ``notebook`` and
``assignment`` which correspond to the names of the notebook and
assignment, not the objects themselves.
"""
return {
"id": self.id,
"name": self.name,
"max_score": self.max_score,
"notebook": self.notebook.name,
"assignment": self.assignment.name
}
def __repr__(self):
return "SolutionCell<{}/{}/{}>".format(
self.assignment.name, self.notebook.name, self.name)
__mapper_args__ = {'polymorphic_identity': 'TaskCell'}
class SourceCell(Base):
__tablename__ = "source_cell"
__table_args__ = (UniqueConstraint('name', 'notebook_id'),)
#: Unique id of the source cell (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Unique human-readable name of the source cell. This need only be unique
#: within the notebook, not across notebooks.
name = Column(String(128), nullable=False)
#: The cell type, either "code" or "markdown"
cell_type = Column(Enum("code", "markdown", name="source_cell_type", validate_strings=True), nullable=False)
#: Whether the cell is locked (e.g. the source saved in the database should
#: be used to overwrite the source of students' cells)
locked = Column(Boolean, default=False, nullable=False)
#: The source code or text of the cell
source = Column(Text())
#: A checksum of the cell contents. This should usually be computed
#: using :func:`nbgrader.utils.compute_checksum`
checksum = Column(String(128))
#: The :class:`~nbgrader.api.Notebook` that this source cell is contained in
notebook = relationship("Notebook", back_populates="source_cells")
#: Unique id of the :attr:`~nbgrader.api.SourceCell.notebook`
notebook_id = Column(String(32), ForeignKey('notebook.id'))
#: The assignment that this cell is contained within, represented by a
#: :class:`~nbgrader.api.Assignment` object
assignment = association_proxy("notebook", "assignment")
def to_dict(self):
"""Convert the source cell object to a JSON-friendly dictionary
representation. Note that this includes keys for ``notebook`` and
``assignment`` which correspond to the names of the notebook and
assignment, not the objects themselves.
"""
return {
"id": self.id,
"name": self.name,
"cell_type": self.cell_type,
"locked": self.locked,
"source": self.source,
"checksum": self.checksum,
"notebook": self.notebook.name,
"assignment": self.assignment.name
}
def __repr__(self):
return "SourceCell<{}/{}/{}>".format(
self.assignment.name, self.notebook.name, self.name)
class Student(Base):
"""Database representation of a student."""
__tablename__ = "student"
#: Unique id of the student. This could be a student ID, a username, an
#: email address, etc., so long as it is unique.
id = Column(String(128), primary_key=True, nullable=False)
#: (Optional) The first name of the student
first_name = Column(String(128))
#: (Optional) The last name of the student
last_name = Column(String(128))
#: (Optional) The student's email address, if the :attr:`~nbgrader.api.Student.id`
#: does not correspond to an email address
email = Column(String(128))
#: A collection of assignments submitted by the student, represented as
#: :class:`~nbgrader.api.SubmittedAssignment` objects
submissions = relationship("SubmittedAssignment", back_populates="student")
#: The overall score of the student across all assignments, computed
#: automatically from the :attr:`~nbgrader.api.SubmittedAssignment.score`
#: of each submitted assignment.
score = None
#: The maximum possible score the student could achieve across all assignments,
#: computed automatically from the :attr:`~nbgrader.api.Assignment.max_score`
#: of each assignment.
max_score = None
#: The LMS user ID, this is mainly for identifying students in your LMS system
#: and was added so teachers and TA's can easily send grades to a LMS such as Canvas and Blackboard.
lms_user_id = Column(String(128), nullable=True)
def to_dict(self):
"""Convert the student object to a JSON-friendly dictionary
representation.
"""
return {
"id": self.id,
"first_name": self.first_name,
"last_name": self.last_name,
"email": self.email,
"score": self.score,
"max_score": self.max_score,
"lms_user_id": self.lms_user_id
}
def __repr__(self):
return "Student<{}>".format(self.id)
class SubmittedAssignment(Base):
"""Database representation of an assignment submitted by a student."""
__tablename__ = "submitted_assignment"
__table_args__ = (UniqueConstraint('assignment_id', 'student_id'),)
#: Unique id of the submitted assignment (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Name of the assignment, inherited from :class:`~nbgrader.api.Assignment`
name = association_proxy("assignment", "name")
#: The master version of this assignment, represented by a
#: :class:`~nbgrader.api.Assignment` object
assignment = relationship("Assignment", back_populates="submissions")
#: Unique id of :attr:`~nbgrader.api.SubmittedAssignment.assignment`
assignment_id = Column(String(32), ForeignKey('assignment.id'))
#: The student who submitted this assignment, represented by a
#: :class:`~nbgrader.api.Student` object
student = relationship("Student", back_populates="submissions")
#: Unique id of :attr:`~nbgrader.api.SubmittedAssignment.student`
student_id = Column(String(128), ForeignKey('student.id'))
#: (Optional) The date and time that the assignment was submitted, in date
#: time format with a UTC timezone
timestamp = Column(DateTime())
#: (Optional) An extension given to the student for this assignment, in
#: time delta format
extension = Column(Interval())
#: A collection of notebooks contained within this submitted assignment,
#: represented by :class:`~nbgrader.api.SubmittedNotebook` objects
notebooks = relationship("SubmittedNotebook", back_populates="assignment")
#: The score assigned to this assignment, automatically calculated from the
#: :attr:`~nbgrader.api.SubmittedNotebook.score` of each notebook within
#: this submitted assignment.
score = None
#: The maximum possible score of this assignment, inherited from
#: :class:`~nbgrader.api.Assignment`
max_score = None
#: The code score assigned to this assignment, automatically calculated from
#: the :attr:`~nbgrader.api.SubmittedNotebook.code_score` of each notebook
#: within this submitted assignment.
code_score = None
#: The maximum possible code score of this assignment, inherited from
#: :class:`~nbgrader.api.Assignment`
max_code_score = None
#: The written score assigned to this assignment, automatically calculated
#: from the :attr:`~nbgrader.api.SubmittedNotebook.written_score` of each
#: notebook within this submitted assignment.
written_score = None
#: The maximum possible written score of this assignment, inherited from
#: :class:`~nbgrader.api.Assignment`
max_written_score = None
#: The task score assigned to this assignment, automatically calculated
#: from the :attr:`~nbgrader.api.SubmittedNotebook.task_score` of each
#: notebook within this submitted assignment.
task_score = None
#: The maximum possible task score of this assignment, inherited from
#: :class:`~nbgrader.api.Assignment`
max_task_score = None
#: Whether this assignment has parts that need to be manually graded,
#: automatically determined from the :attr:`~nbgrader.api.SubmittedNotebook.needs_manual_grade`
#: attribute of each notebook.
needs_manual_grade = None
#: The penalty (>= 0) given for submitting the assignment late.
#: Automatically determined from the
#: :attr:`~nbgrader.api.SubmittedNotebook.late_submission_penalty`
#: attribute of each notebook.
late_submission_penalty = None
@property
def duedate(self) -> datetime.datetime:
"""The duedate of this student's assignment, which includes any extension
given, if applicable, and which is just the regular assignment duedate
otherwise.
"""
orig_duedate = self.assignment.duedate
if self.extension is not None:
return orig_duedate + self.extension
else:
return orig_duedate
@property
def total_seconds_late(self) -> float:
"""The number of seconds that this assignment was turned in past the
duedate (including extensions, if any). If the assignment was turned in
before the deadline, this value will just be zero.
"""
if self.timestamp is None or self.duedate is None:
return 0
else:
return max(0, (self.timestamp - self.duedate).total_seconds())
def to_dict(self):
"""Convert the submitted assignment object to a JSON-friendly dictionary
representation. Note that this includes a ``student`` key which is the
unique id of the student, not the object itself.
"""
return {
"id": self.id,
"name": self.name,
"student": self.student.id,
"first_name": self.student.first_name,
"last_name": self.student.last_name,
"timestamp": self.timestamp.isoformat() if self.timestamp is not None else None,
"score": self.score,
"max_score": self.max_score,
"code_score": self.code_score,
"max_code_score": self.max_code_score,
"written_score": self.written_score,
"max_written_score": self.max_written_score,
"task_score": self.task_score,
"max_task_score": self.max_task_score,
"needs_manual_grade": self.needs_manual_grade
}
def __repr__(self) -> str:
return "SubmittedAssignment<{} for {}>".format(self.name, self.student.id)
class SubmittedNotebook(Base):
"""Database representation of a notebook submitted by a student."""
__tablename__ = "submitted_notebook"
__table_args__ = (UniqueConstraint('notebook_id', 'assignment_id'),)
#: Unique id of the submitted notebook (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Name of the notebook, inherited from :class:`~nbgrader.api.Notebook`
name = association_proxy("notebook", "name")
#: The submitted assignment this notebook is a part of, represented by a
#: :class:`~nbgrader.api.SubmittedAssignment` object
assignment = relationship("SubmittedAssignment", back_populates="notebooks")
#: Unique id of :attr:`~nbgrader.api.SubmittedNotebook.assignment`
assignment_id = Column(String(32), ForeignKey('submitted_assignment.id'))
#: The master version of this notebook, represented by a
#: :class:`~nbgrader.api.Notebook` object
notebook = relationship("Notebook", back_populates="submissions")
#: Unique id of :attr:`~nbgrader.api.SubmittedNotebook.notebook`
notebook_id = Column(String(32), ForeignKey('notebook.id'))
#: Collection of associated with this submitted notebook, represented
#: by :class:`~nbgrader.api.Grade` objects
grades = relationship("Grade", back_populates="notebook")
#: Collection of comments associated with this submitted notebook, represented
#: by :class:`~nbgrader.api.Comment` objects
comments = relationship("Comment", back_populates="notebook")
#: The student who submitted this notebook, represented by a
#: :class:`~nbgrader.api.Student` object
student = association_proxy('assignment', 'student')
#: Whether this assignment has been flagged by a human grader
flagged = Column(Boolean, default=False)
#: The score assigned to this notebook, automatically calculated from the
#: :attr:`~nbgrader.api.Grade.score` of each grade cell within
#: this submitted notebook.
score = None
#: The maximum possible score of this notebook, inherited from
#: :class:`~nbgrader.api.Notebook`
max_score = None
#: The code score assigned to this notebook, automatically calculated from
#: the :attr:`~nbgrader.api.Grade.score` and :attr:`~nbgrader.api.GradeCell.cell_type`
#: of each grade within this submitted notebook.
code_score = None
#: The maximum possible code score of this notebook, inherited from
#: :class:`~nbgrader.api.Notebook`
max_code_score = None
#: The written score assigned to this notebook, automatically calculated from
#: the :attr:`~nbgrader.api.Grade.score` and :attr:`~nbgrader.api.GradeCell.cell_type`
#: of each grade within this submitted notebook.
written_score = None
#: The maximum possible written score of this notebook, inherited from
#: :class:`~nbgrader.api.Notebook`
max_written_score = None
#: Whether this notebook has parts that need to be manually graded,
#: automatically determined from the :attr:`~nbgrader.api.Grade.needs_manual_grade`
#: attribute of each grade.
needs_manual_grade = None
#: Whether this notebook contains autograder tests that failed to pass,
#: automatically determined from the :attr:`~nbgrader.api.Grade.failed_tests`
#: attribute of each grade.
failed_tests = None
#: The penalty (>= 0) given for submitting the assignment late. Updated
#: by the :class:`~nbgrader.plugins.LateSubmissionPlugin`.
late_submission_penalty = Column(Float(0))
def to_dict(self):
"""Convert the submitted notebook object to a JSON-friendly dictionary
representation. Note that this includes a key for ``student`` which is
the unique id of the student, not the actual student object.
"""
return {
"id": self.id,
"name": self.name,
"student": self.student.id,
"last_name": self.student.last_name,
"first_name": self.student.first_name,
"score": self.score,
"max_score": self.max_score,
"code_score": self.code_score,
"max_code_score": self.max_code_score,
"written_score": self.written_score,
"max_written_score": self.max_written_score,
"task_score": self.task_score,
"max_task_score": self.max_task_score,
"needs_manual_grade": self.needs_manual_grade,
"failed_tests": self.failed_tests,
"flagged": self.flagged,
}
def __repr__(self):
return "SubmittedNotebook<{}/{} for {}>".format(
self.assignment.name, self.name, self.student.id)
class Grade(Base):
"""Database representation of a grade assigned to the submitted version of
a grade cell.
"""
__tablename__ = "grade"
__table_args__ = (UniqueConstraint('cell_id', 'notebook_id'),)
#: Unique id of the grade (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Unique name of the grade cell, inherited from :class:`~nbgrader.api.GradeCell`
name = association_proxy('cell', 'name')
#: The submitted assignment that this grade is contained in, represented by
#: a :class:`~nbgrader.api.SubmittedAssignment` object
assignment = association_proxy('notebook', 'assignment')
#: The submitted notebook that this grade is assigned to, represented by a
#: :class:`~nbgrader.api.SubmittedNotebook` object
notebook = relationship("SubmittedNotebook", back_populates="grades")
#: Unique id of :attr:`~nbgrader.api.Grade.notebook`
notebook_id = Column(String(32), ForeignKey('submitted_notebook.id'))
#: The master version of the cell this grade is assigned to, represented by
#: a :class:`~nbgrader.api.GradeCell` object.
cell = relationship('BaseCell', back_populates='grades')
#: Unique id of :attr:`~nbgrader.api.Grade.cell`
cell_id = Column(String(32), ForeignKey('base_cell.id'))
#: The type of cell this grade corresponds to, inherited from
#: :class:`~nbgrader.api.GradeCell`
cell_type = association_proxy('cell', 'cell_type')
#: The student who this grade is assigned to, represented by a
#: :class:`~nbgrader.api.Student` object
student = association_proxy('notebook', 'student')
#: Score assigned by the autograder
auto_score = Column(Float())
#: Score assigned by a human grader
manual_score = Column(Float())
#: Extra credit assigned by a human grader
extra_credit = Column(Float())
#: Whether a score needs to be assigned manually. This is True by default.
needs_manual_grade = Column(Boolean, default=True, nullable=False)
#: The overall score, computed automatically from the
#: :attr:`~nbgrader.api.Grade.auto_score` and :attr:`~nbgrader.api.Grade.manual_score`
#: values. If neither are set, the score is zero. If both are set, then the
#: manual score takes precedence. If only one is set, then that value is used
#: for the score.
score = column_property(case(
[
(manual_score != None, manual_score + case([(extra_credit != None, extra_credit)], else_=literal_column("0.0"))),
(auto_score != None, auto_score + case([(extra_credit != None, extra_credit)], else_=literal_column("0.0")))
],
else_=literal_column("0.0")
))
#: The maximum possible score that can be assigned, inherited from
#: :class:`~nbgrader.api.GradeCell`
max_score_gradecell = None
max_score_taskcell = None
@property
def max_score(self):
if self.max_score_taskcell:
return self.max_score_taskcell
else:
return self.max_score_gradecell
#: Whether the autograded score is a result of failed autograder tests. This
#: is True if the autograder score is zero and the cell type is "code", and
#: otherwise False.
failed_tests = None
def to_dict(self):
"""Convert the grade object to a JSON-friendly dictionary representation.
Note that this includes keys for ``notebook`` and ``assignment`` which
correspond to the name of the notebook and assignment, not the actual
objects. It also includes a key for ``student`` which corresponds to the
unique id of the student, not the actual student object.
"""
return {
"id": self.id,
"name": self.name,
"notebook": self.notebook.name,
"assignment": self.assignment.name,
"student": self.student.id,
"auto_score": self.auto_score,
"manual_score": self.manual_score,
"extra_credit": self.extra_credit,
"max_score": self.max_score,
"needs_manual_grade": self.needs_manual_grade,
"failed_tests": self.failed_tests,
"cell_type": self.cell_type
}
def __repr__(self):
return "Grade<{}/{}/{} for {}>".format(
self.assignment.name, self.notebook.name, self.name, self.student.id)
class Comment(Base):
"""Database representation of a comment on a cell in a submitted notebook."""
__tablename__ = "comment"
__table_args__ = (UniqueConstraint('cell_id', 'notebook_id'),)
#: Unique id of the comment (automatically generated)
id = Column(String(32), primary_key=True, default=new_uuid)
#: Unique name of the solution cell, inherited from :class:`~nbgrader.api.SolutionCell`
name = association_proxy('cell', 'name')
#: The submitted assignment that this comment is contained in, represented by
#: a :class:`~nbgrader.api.SubmittedAssignment` object
assignment = association_proxy('notebook', 'assignment')
#: The submitted notebook that this comment is assigned to, represented by a
#: :class:`~nbgrader.api.SubmittedNotebook` object
notebook = relationship("SubmittedNotebook", back_populates="comments")
#: Unique id of :attr:`~nbgrader.api.Comment.notebook`
notebook_id = Column(String(32), ForeignKey('submitted_notebook.id'))
#: The master version of the cell this comment is assigned to, represented by
#: a :class:`~nbgrader.api.SolutionCell` object.
cell = relationship('BaseCell', back_populates='comments')
#: Unique id of :attr:`~nbgrader.api.Comment.cell`
cell_id = Column(String(32), ForeignKey('base_cell.id'))
#: The student who this comment is assigned to, represented by a
#: :class:`~nbgrader.api.Student` object
student = association_proxy('notebook', 'student')
#: A comment which is automatically assigned by the autograder
auto_comment = Column(Text())
#: A comment which is assigned manually
manual_comment = Column(Text())
#: The overall comment, computed automatically from the
#: :attr:`~nbgrader.api.Comment.auto_comment` and
#: :attr:`~nbgrader.api.Comment.manual_comment` values. If neither are set,
#: the comment is None. If both are set, then the manual comment
#: takes precedence. If only one is set, then that value is used for the
#: comment.
comment = column_property(case(
[
(manual_comment != None, manual_comment),
(auto_comment != None, auto_comment)
],
else_=None
))
def to_dict(self):
"""Convert the comment object to a JSON-friendly dictionary representation.
Note that this includes keys for ``notebook`` and ``assignment`` which
correspond to the name of the notebook and assignment, not the actual
objects. It also includes a key for ``student`` which corresponds to the
unique id of the student, not the actual student object.
"""
return {
"id": self.id,
"name": self.name,
"notebook": self.notebook.name,
"assignment": self.assignment.name,
"student": self.student.id,
"auto_comment": self.auto_comment,
"manual_comment": self.manual_comment
}
def __repr__(self):
return "Comment<{}/{}/{} for {}>".format(
self.assignment.name, self.notebook.name, self.name, self.student.id)
class Course(Base):
"""Table to store the courses"""
__tablename__ = "course"
id = Column(String(128), unique=True, primary_key=True, nullable=False)
assignments = relationship("Assignment", back_populates="course")
def __repr__(self):
return "Course<{}>".format(self.id)
## Needs manual grade
SubmittedNotebook.needs_manual_grade = column_property(
exists().where(and_(
Grade.notebook_id == SubmittedNotebook.id,
Grade.needs_manual_grade))
.correlate_except(Grade), deferred=True)
SubmittedAssignment.needs_manual_grade = column_property(
exists().where(and_(
SubmittedNotebook.assignment_id == SubmittedAssignment.id,
Grade.notebook_id == SubmittedNotebook.id,
Grade.needs_manual_grade))
.correlate_except(Grade), deferred=True)
Notebook.needs_manual_grade = column_property(
exists().where(and_(
Notebook.id == SubmittedNotebook.notebook_id,
Grade.notebook_id == SubmittedNotebook.id,
Grade.needs_manual_grade))
.correlate_except(Grade), deferred=True)
# Overall scores
SubmittedNotebook.score = column_property(
select([func.coalesce(func.sum(Grade.score), 0.0)])
.where(Grade.notebook_id == SubmittedNotebook.id)
.correlate_except(Grade)
.scalar_subquery(), deferred=True)
SubmittedAssignment.score = column_property(
select([func.coalesce(func.sum(Grade.score), 0.0)])
.where(and_(
SubmittedNotebook.assignment_id == SubmittedAssignment.id,
Grade.notebook_id == SubmittedNotebook.id))
.correlate_except(Grade)
.scalar_subquery(), deferred=True)
Student.score = column_property(
select([func.coalesce(func.sum(Grade.score), 0.0)])
.where(and_(
SubmittedAssignment.student_id == Student.id,
SubmittedNotebook.assignment_id == SubmittedAssignment.id,
Grade.notebook_id == SubmittedNotebook.id))
.correlate_except(Grade)
.scalar_subquery(), deferred=True)
# Overall max scores
Grade.max_score_gradecell = column_property(
select([func.coalesce(GradeCell.max_score, 0.0)])
.select_from(GradeCell)
.where(Grade.cell_id == GradeCell.id)
.correlate_except(GradeCell)
.scalar_subquery(), deferred=True)
Grade.max_score_taskcell = column_property(
select([func.coalesce(TaskCell.max_score, 0.0)])
.select_from(TaskCell)
.where(Grade.cell_id == TaskCell.id)
.correlate_except(TaskCell)
.scalar_subquery(), deferred=True)
# a grade is either from a grade cell or a task cell , so only one will not be none
Grade.max_score = column_property(func.coalesce(Grade.max_score_gradecell, Grade.max_score_taskcell, 0.0), deferred=True)