forked from Ram-N/OM-API-Utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_api.py
1507 lines (1330 loc) · 45.4 KB
/
data_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 backend import Class, User, List, Item, Event, AssignmentTemplate, Assignment
from bson.errors import InvalidId
from bson.objectid import ObjectId
from common_core import CommonCore
from datetime import datetime
from libraries.python import cookies
from libraries.python.cors_util import add_cors_headers
from libraries.python.db_models import create_generic_document_from_data
from libraries.python.db_models import get_generic_document, ValidationError
from libraries.python.util import permute_indices_by_weight
from libraries.python.web_util import encode_json, decode_json
from libraries.python.web_util import parse_int_param, parse_int_param_as_bool
import logging
import util
from pymongo.errors import DuplicateKeyError
from libraries.python.util import error_response, HTTPError
from api_util import OpenMindsAPIHandler
import adaptive_model
from auth import login_optional, login_required
from auth import public_api_auth, private_api_auth
from auth import get_user_cookie, set_user_cookie
import json
import pymongo
import web
import littlelives_info
urls =(
# SEMI-PRIVATE APIS
'/authenticate/?', 'AuthenticateHandler',
'/classes/?', 'ClassesHandler',
'/classes/([^/]+)/?', 'ClassHandler',
'/users/?', 'UsersHandler',
'/users/([^/]+)/?', 'UserHandler',
'/lists/?', 'ListsHandler',
'/lists/([^/]+)/?', 'ListHandler',
'/lists/([^/]+)/([^/]+)/?', 'ItemHandler',
# ASSIGNMENTS
'/assignment_templates/?', 'AssignmentTemplatesHandler',
'/assignment_templates/([^/]+)/?', 'AssignmentTemplateHandler',
'/assignments/?', 'AssignmentsHandler',
'/assignments/([^/]+)/?', 'AssignmentHandler',
# PRIVATE APIS
'/events/?', 'EventsHandler',
'/common_core/([^/]+)/?', 'CommonCoreHandler',
'/littlelives/auth/?', 'LittleLivesAuthenticateHandler',
'/littlelives/user_info/?', 'LittleLivesUsersHandler',
# TEMP APIS
'/leaderboard/?', 'LeaderboardHandler',
)
app = web.application(urls, locals())
def can_see_student_data(auth_user, student_user_id):
"""
Can the authenticated user view data for this student?
Optimal answer: yes, if user is student, teacher of student, or parent of
student.
FIXME(dbanks)
For now, just say yes.
"""
return True
def can_see_class_data(auth_user, class_id):
"""
Can the authenticated user see data about this class?
Yes, if user is creator of class or instructor of class.
"""
class_spec = {
'_id': class_id,
'$or': {
'creator': auth_user._id,
'instructor': str(auth_user.id)
}
}
class_item = Class.collection.find_one(class_spec)
return class_item is not None
def get_lists(auth_user, params):
num = parse_int_param(params.num, 50)
grade = parse_int_param(params.grade, None)
section = parse_int_param(params.section, None)
if params.search in ('all', 'created'):
search = params.search
else:
search = 'all'
spec = {'deleted': False}
if search == 'created':
spec['creator'] = auth_user._id
if grade is not None:
spec['grade'] = grade
if params.standard is not None:
spec['standard'] = params.standard
# Only add the section to the spec if a standard is also defined.
if params.section is not None:
spec['section'] = section
item_lists = List.collection.find(spec).limit(num)
return item_lists
def adaptive_sort_item_list(json_item_list, auth_user):
"""
Sort the items in this list by order of 'adaptive learning desirability':
A < B if we think given user should practice on A instead of B.
"""
# Get any stats for this user and these items.
item_ids = [ObjectId(item['id']) for item in json_item_list]
spec = {'userId': auth_user._id, 'itemId': {'$in': item_ids}}
item_stats = list(adaptive_model.UserItemInfo.collection.find(spec))
# Make an array tying item json (what we will be returning) to any
# known stats or scores,
item_blobs = []
for json_item in json_item_list:
item_blob = {}
item_blob['json'] = json_item
item_blob['stat'] = None
item_blob['masteryScore'] = -1
for item_stat in item_stats:
if str(item_stat.itemId) == json_item['id']:
item_blob['stat'] = item_stat
item_blob['masteryScore'] = item_stat.calculate_mastery_score()
item_blob['masteryThreshold'] = item_stat.get_mastery_threshold()
break
item_blobs.append(item_blob)
weights = adaptive_model.get_adaptive_weights(item_blobs)
indices = permute_indices_by_weight(weights)
new_json_list = []
for index in indices:
new_json_list.append(item_blobs[index]['json'])
logging.debug(" " + item_blobs[index]['json'].get('word', 'word'))
logging.debug(" weight:" + str(weights[index]))
logging.debug(" MasteryScore:" + str(item_blobs[index]['masteryScore']))
return new_json_list
class AuthenticateHandler(object):
'''
Handler to authenticate a user based on a username and password.
'''
def GET(self):
'''
Authenticates the user based on a username and password. If the
authentication is successful, returns a JSON object containing a user id
and the auth token. The auth token should be written to a cookie that gets
sent on subsequent requests.
'''
params = web.input(username=None, password=None)
if params.username == None or params.password == None:
logging.warn('Missing username or password.')
return error_response(400)
try:
user = User.collection.find_one(
{'username': params.username, 'deleted': False})
except Exception, e:
logging.error(e)
return error_response(500, 'Server Error')
if not user:
return error_response(401, 'Incorrect username')
if not user.check_password(params.password):
return error_response(401, 'Incorrect password')
user_id = str(user._id)
auth_token = set_user_cookie(user_id)
response = {
'id': user_id,
'authToken': auth_token
}
return encode_json(response)
class ClassesHandler(OpenMindsAPIHandler):
'''
Handler for retrieving basic information about classes and creating
new classes.
'''
@add_cors_headers
@public_api_auth
def GET(self, auth_user=None, auth_app_id=None):
'''
Returns a JSON array of basic information about classes owned
by the authenticated user.
'''
spec = {
'creator': auth_user._id,
'deleted': False,
}
try:
classes = Class.collection.find(spec)
formatted_classes = [c.formatted_dict() for c in classes]
return encode_json(formatted_classes)
except Exception, e:
logging.error(e)
return error_response(500, 'Server Error')
@add_cors_headers
@public_api_auth
def POST(self, auth_user=None, auth_app_id=None):
'''
Creates a new class and returns a JSON object containing the
id for the new class.
'''
params = web.input(data=None)
try:
if params.data:
data = decode_json(params.data)
else:
data = decode_json(web.ctx.data)
Class.validate(data)
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
try:
school_class = Class()
school_class.update_class(data)
school_class.reset_code()
school_class.set_creator(auth_user)
school_class.save()
response = {
'id': str(school_class._id),
'code': school_class.code,
}
return encode_json(response)
except Exception, e:
return error_response(500, 'Server Error')
class ClassHandler(OpenMindsAPIHandler):
'''
Handler for retrieving extended information about a specific class,
or updating/deleting a class' information.
'''
@add_cors_headers
@public_api_auth
def GET(self, class_id=None, auth_user=None, auth_app_id=None):
'''
Return a JSON object containing extended information about the
specific class.
'''
try:
school_class = get_generic_document(class_id, Class)
except HTTPError, e:
return e.error_response()
formatted_dict = school_class.formatted_dict(extended=True)
return encode_json(formatted_dict)
@add_cors_headers
@public_api_auth
def PUT(self, class_id, auth_user=None, auth_app_id=None):
'''
Update the given class, and returns a JSON object containing the
new timestamp.
'''
try:
school_class = get_generic_document(class_id, Class)
except HTTPError, e:
return e.error_response()
if not school_class.user_can_update(auth_user):
message = 'Class cannot be modified by the user'
logging.warn(message)
return error_response(403, message)
try:
data = decode_json(web.ctx.data)
Class.validate(data)
# Convert string user ids to object ids. If an object id is not
# valid, return an error response code.
if 'instructor' in data:
data['instructor'] = ObjectId(data['instructor'])
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
try:
school_class.update_class(data)
school_class.save()
update_json = {'updated': school_class.updated_timestamp()}
if 'resetCode' in data:
# Since the class code change happens on the server, we need
# to send the new code in the response.
update_json['code'] = school_class.code
return encode_json(update_json)
except Exception, e:
logging.error(e)
return error_response(500)
@add_cors_headers
@public_api_auth
def DELETE(self, class_id, auth_user=None, auth_app_id=None):
'''
Delete the given class, and returns a JSON object containing a
success notification.
'''
try:
school_class = get_generic_document(class_id, Class)
except HTTPError, e:
return e.error_response()
if not school_class.user_can_update(auth_user):
message = 'Class cannot be modified by the user'
logging.warn(message)
return error_response(403, message)
try:
school_class.delete()
school_class.save()
# Delete all assignments associated with this class.
Assignment.collection.update({
'classId': class_id,
'deleted': False,
}, {
'$set': {
'deleted': True
}
}, multi=True)
update_json = {'success': True}
return encode_json(update_json)
except Exception, e:
logging.error(e)
return error_response(500)
class UsersHandler(OpenMindsAPIHandler):
'''
Handler for retrieving basic information about users and creating
new users.
'''
@add_cors_headers
@public_api_auth
def GET(self, auth_user=None, auth_app_id=None):
'''
Returns a JSON array of basic information about users.
'''
params = web.input(assignment_id=None, class_id=None)
class_id = None
if params.class_id is not None:
try:
class_id = ObjectId(params.class_id)
except Exception, e:
logging.warn(e)
return error_response(400)
if class_id is None:
# Just find all users created by authenticated user.
users_spec = {
'creator': auth_user._id,
'deleted': False,
}
else:
cspec = {'_id': class_id}
try:
class_obj = Class.collection.find_one(cspec)
except Exception, e:
logging.error(e)
return error_response(500)
if class_obj is None:
return error_response(404)
user_id_str_set = set()
if 'students' in class_obj:
for user_id_str in class_obj['students']:
user_id_str_set.add(user_id_str)
try:
user_ids = [ObjectId(user_id_str) for user_id_str in user_id_str_set]
users_spec = {
'deleted': False,
'_id': {'$in': user_ids},
}
except Exception, e:
logging.error(e)
return error_response(500)
try:
users = User.collection.find(users_spec)
# Return private data iff we're looking at users created by
# authenticated user.
formatted_users = [
u.formatted_dict(private_data=(class_id is None)) for u in users]
return encode_json(formatted_users)
except Exception, e:
logging.error(e)
return error_response(500)
@add_cors_headers
@public_api_auth
def POST(self, auth_user=None, auth_app_id=None):
'''
Creates a new user and returns a JSON object containing the
id and auth token for the new user.
'''
params = web.input(data=None)
try:
if params.data:
data = decode_json(params.data)
else:
data = decode_json(web.ctx.data)
User.validate(data)
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
try:
user = User()
user.update_user(data)
user.set_creator(auth_user)
token = data.get('token', None)
if auth_user:
user.add_to_acl(auth_user, token)
user.reset_oauth()
user.save()
auth_token = get_user_cookie(user._id)
response = {
'id': str(user._id),
'authToken': auth_token
}
return encode_json(response)
except DuplicateKeyError, e:
logging.error(e)
return error_response(400, 'That username already exists.')
except Exception, e:
logging.error(e)
return error_response(500, 'Server Error')
class UserHandler(OpenMindsAPIHandler):
'''
Handler for retrieving extended information about a specific user,
or updating/deleting a user's information.
'''
def parse_user_id(self, user_id, auth_user):
if user_id == 'me':
return 'id', auth_user._id
elif user_id.startswith('token:'):
return 'token', user_id[6:]
else:
return 'id', ObjectId(user_id)
@add_cors_headers
@public_api_auth
def GET(self, user_id, auth_user=None, auth_app_id=None):
'''
Return a JSON object containing extended information about the
specific user.
'''
try:
id_type, user_id = self.parse_user_id(user_id, auth_user)
except Exception, e:
logging.warn(e)
return error_response(400, 'Not a valid user id')
if user_id == auth_user._id:
# User is accessing own information.
user = auth_user
user_dict = auth_user.formatted_dict()
else:
# User is accessing another user's information.
if id_type == 'id':
# Accessing another user by id.
# NOTE(adam): Perhaps this should be forbidden for now?
user = User.collection.find_one({'_id': user_id, 'deleted': False})
else:
# Accessing another user with a token.
auth_user_key = 'acl.%s.token' % str(auth_user._id)
user = User.collection.find_one({
auth_user_key: user_id,
'deleted': False,
})
if not user:
message = 'User does not exist'
logging.warn(message)
return error_response(404, message)
user_dict = user.formatted_dict()
try:
num_mastered_words = adaptive_model.UserItemInfo.collection.find({
'userId': user._id,
'totalOutcomes': {
'$gte': adaptive_model.MIN_TOTAL_OUTCOMES_FOR_MASTERY
},
'average': {
'$gte': adaptive_model.MIN_AVERAGE_FOR_MASTERY
},
'volatility': {
'$lte': adaptive_model.MAX_VOLATILITY_FOR_MASTERY
}
}).count()
except Exception, e:
logging.error(e)
return error_response(500)
user_dict['numMastered'] = num_mastered_words
return encode_json(user_dict)
@add_cors_headers
@public_api_auth
def PUT(self, user_id, auth_user=None, auth_app_id=None):
'''
Updates the given user, and returns a JSON object containing
the new timestamp.
'''
try:
id_type, user_id = self.parse_user_id(user_id, auth_user)
except Exception, e:
logging.warn(e)
return error_response(400, 'Not a valid user id')
try:
data = decode_json(web.ctx.data)
User.validate(data)
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
user = None
try:
if user_id == auth_user._id:
# User is modifying itself.
user = auth_user
else:
# User is attempting to modify other user.
if id_type == 'id':
# Accessing another user by id.
user = User.collection.find_one({'_id': user_id, 'deleted': False})
else:
# Accessing another user with a token.
auth_user_key = 'acl.%s.token' % str(auth_user._id)
user = User.collection.find_one({
auth_user_key: user_id
})
except Exception, e:
logging.error(e)
return error_response(500, 'Server Error')
if not user:
message = 'User does not exist'
logging.warn(message)
return error_response(404, message)
if not user.user_can_update(auth_user):
message = 'Forbidden'
logging.warn(message)
return error_response(403, message)
try:
user.update_user(data)
user.save()
update_json = {'updated': user.updated_timestamp()}
return encode_json(update_json)
except DuplicateKeyError, e:
logging.error(e)
return error_response(500, 'That username already exists.')
except Exception, e:
logging.error(e)
return error_response(500, 'Server Error')
@add_cors_headers
@public_api_auth
def DELETE(self, user_id, auth_user=None, auth_app_id=None):
'''
Delete the given user, and returns a JSON object containing
a success notification.
'''
try:
id_type, user_id = self.parse_user_id(user_id, auth_user)
except Exception, e:
logging.warn(e)
return error_response(400, 'Not a valid user id')
user = None
try:
if user_id == auth_user._id:
# User is modifying itself.
user = auth_user
else:
# User is attempting to modify other user.
if id_type == 'id':
# Accessing another user by id.
user = User.collection.find_one({'_id': user_id, 'deleted': False})
else:
# Accessing another user with a token.
auth_user_key = 'acl.%s.token' % str(auth_user._id)
user = User.collection.find_one({
auth_user_key: user_id,
'deleted': False,
})
except Exception, e:
logging.error(e)
return error_response(500, 'Server Error')
if not user:
message = 'User does not exist'
logging.warn(message)
return error_response(404, message)
if not user.user_can_update(auth_user):
message = 'Forbidden'
logging.warn(message)
return error_response(403, message)
try:
user.delete()
user.save()
update_json = {'success': True}
return encode_json(update_json)
except Exception, e:
logging.error(e)
return error_response(500, 'Server Error')
class AssignmentTemplatesHandler(OpenMindsAPIHandler):
'''
Handler for retrieving basic information about assignment templates and
creating new assignment template.
'''
@add_cors_headers
@public_api_auth
def GET(self, auth_user=None, auth_app_id=None):
'''
Returns a JSON array of basic information about assignment templates.
FIXME(dbanks)
Right now you get all assignment templates.
We may want to control that somehow so that some templates (created
by us) are public-domain. Others, auth_user has to be on acl for that
template.
'''
params = web.input(num=50)
depth = parse_int_param(util.get_header('X-OpenMinds-Depth'), 0)
try:
num = parse_int_param(params.num, 50)
spec = {'deleted': False}
templates = AssignmentTemplate.collection.find(spec).limit(num)
formatted_templates = \
[template.formatted_dict(depth=depth) for template in templates]
return encode_json(formatted_templates)
except Exception, e:
logging.error(e)
return error_response(500)
@add_cors_headers
@public_api_auth
def POST(self, auth_user=None, auth_app_id=None):
'''
Creates a new AssignmentTemplate and returns a JSON object containing the
id for the new AssignmentTemplate.
'''
params = web.input(data=None)
depth = parse_int_param(util.get_header('X-OpenMinds-Depth'), 0)
try:
if params.data:
data = decode_json(params.data)
else:
data = decode_json(web.ctx.data)
AssignmentTemplate.validate(data)
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
try:
convert_assignment_data_to_db_format(data)
assignment_template = AssignmentTemplate(data)
assignment_template.set_creator(auth_user)
assignment_template.save()
formatted_dict = assignment_template.formatted_dict(depth=depth)
return encode_json(formatted_dict)
except:
return error_response(500, 'Server Error')
class AssignmentTemplateHandler(OpenMindsAPIHandler):
"""
Handler for getting and updating AssignmentTemplates
"""
@add_cors_headers
@public_api_auth
def GET(self, assignment_template_id, auth_user=None, auth_app_id=None):
'''
Return a JSON object containing information about the
specific AssignmentTemplate.
'''
try:
assignment_template = get_generic_document(
assignment_template_id, AssignmentTemplate)
except HTTPError, e:
return e.error_response()
depth = parse_int_param(util.get_header('X-OpenMinds-Depth'), 0)
formatted_dict = assignment_template.formatted_dict(depth=depth)
return encode_json(formatted_dict)
@add_cors_headers
@public_api_auth
def PUT(self, assignment_template_id, auth_user=None, auth_app_id=None):
'''
Update existing AssignmentTemplate.
'''
try:
assignment_template = get_generic_document(
assignment_template_id, AssignmentTemplate)
except HTTPError, e:
return e.error_response()
params = web.input(data=None)
try:
if params.data:
data = decode_json(params.data)
else:
data = decode_json(web.ctx.data)
AssignmentTemplate.validate(data)
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
if not assignment_template.user_can_update(auth_user):
return error_response(
403, 'Assignment Template cannot be modified by the user')
try:
convert_assignment_data_to_db_format(data)
assignment_template.update(data)
assignment_template.save()
update_json = {'updated': assignment_template.updated_timestamp()}
return encode_json(update_json)
except Exception, e:
logging.error(e)
return error_response(500)
class AssignmentsHandler(OpenMindsAPIHandler):
'''
Handler for retrieving basic information about assignments and creating
new assignment.
'''
@add_cors_headers
@public_api_auth
def GET(self, auth_user=None, auth_app_id=None):
'''
Returns a JSON array of basic information about assignment.
'''
params = web.input(
student_user_id=None, class_id=None, availability=None, num=50)
depth = parse_int_param(util.get_header('X-OpenMinds-Depth'), 0)
try:
num = parse_int_param(params.num, 50)
except Exception, e:
logging.error(e)
return error_response(400, 'Could not parse num parameter.')
try:
# If student_user_id is present, we're asking for all assignments assigned
# to user X. Access is limited by auth_users rights to see student X's
# info.
#
# If student_user_id is not present but class_id is present, we're asking
# for all assignments given to that class.
# Access is limited by auth_users rights to see class X info.
#
# If both student_user_id and class_id are missing, we assume auth_user is
# a teacher and we look for all assignments created by that teacher.
assignment_spec = {
'deleted': False,
}
if params.student_user_id is not None:
try:
# Note we don't actually use the converted id, we can search with
# just the plain string. But it's a nice sanity check.
student_user_id = ObjectId(params.student_user_id)
except Exception, e:
logging.warn(e)
return error_response(400, 'student_user_id is not a valid id')
if not can_see_student_data(auth_user, student_user_id):
return error_response(401)
# Find all classes he belongs to.
classes_spec = {'students': params.student_user_id}
classes_list = Class.collection.find(classes_spec)
# Now find all assignments for these classes.
class_ids = []
for class_doc in classes_list:
class_ids.append(str(class_doc._id))
assignment_spec['classId'] = {'$in': class_ids}
elif params.class_id is not None:
try:
class_id = ObjectId(params.class_id)
except Exception, e:
logging.warn(e)
return error_response(400, 'class_id is not a valid id')
if not can_see_class_data(auth_user, class_id):
return error_response(401)
assignment_spec['classId'] = params.class_id
else:
assignment_spec['creator'] = auth_user._id
if params.availability is not None:
assignment_spec['availability'] = parse_int_param(
params.availability, Assignment.AVAILABILITY_OPEN)
assignments = Assignment.collection.find(assignment_spec).limit(num)
formatted_assignments = [assignment.formatted_dict(depth=depth)
for assignment in assignments]
return encode_json(formatted_assignments)
except Exception, e:
logging.error(e)
return error_response(500)
@add_cors_headers
@public_api_auth
def POST(self, auth_user=None, auth_app_id=None):
'''
Creates a new Assignment and returns a JSON object containing the
id for the new Assignment.
You could pass up a fully specified assignment, but as a convenience we also
allow you to pass up an assignment template id, which will fill in
all the data for you.
'''
params = web.input(data=None)
depth = parse_int_param(util.get_header('X-OpenMinds-Depth'), 0)
try:
if params.data:
data = decode_json(params.data)
else:
data = decode_json(web.ctx.data)
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
if 'assignmentTemplateId' in data:
try:
assignment_template = get_generic_document(
data['assignmentTemplateId'], AssignmentTemplate)
del data['assignmentTemplateId']
except HTTPError, e:
return e.error_response()
formatted_data = assignment_template.formatted_dict(depth=0)
if 'units' in formatted_data:
data['units'] = formatted_data['units']
if 'name' in formatted_data:
data['name'] = formatted_data['name']
try:
Assignment.validate(data)
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
try:
convert_assignment_data_to_db_format(data)
assignment = Assignment(data)
assignment.set_creator(auth_user)
assignment.save()
response = assignment.formatted_dict(depth=depth)
return encode_json(response)
except Exception, e:
logging.error(e)
logging.error(500, 'Server Error')
class AssignmentHandler(OpenMindsAPIHandler):
"""
Handler for getting and updating Assignments
"""
@add_cors_headers
@public_api_auth
def GET(self, assignment_id, auth_user=None, auth_app_id=None):
'''
Return a JSON object containing information about the
specific Assignment.
'''
try:
assignment = get_generic_document(assignment_id, Assignment)
except HTTPError, e:
return e.error_response()
depth = parse_int_param(util.get_header('X-OpenMinds-Depth'), 0)
formatted_dict = assignment.formatted_dict(depth=depth)
return encode_json(formatted_dict)
@add_cors_headers
@public_api_auth
def PUT(self, assignment_id, auth_user=None, auth_app_id=None):
'''
Update existing Assignment.
'''
try:
assignment = get_generic_document(assignment_id, Assignment)
except HTTPError, e:
return e.error_response()
params = web.input(data=None)
try:
if params.data:
data = decode_json(params.data)
else:
data = decode_json(web.ctx.data)
Assignment.validate(data)
except ValueError, e:
logging.warn(e)
return error_response(400, 'Could not parse JSON')
except ValidationError, e:
logging.warn(e)
return error_response(400, e.error)
if not assignment.user_can_update(auth_user):
return error_response(403, 'Assignment cannot be modified by the user')
try:
convert_assignment_data_to_db_format(data)
assignment.update(data)
assignment.save()
update_json = {'updated': assignment.updated_timestamp()}
return encode_json(update_json)
except Exception, e:
logging.error(e)
return error_response(500)
def convert_assignment_data_to_db_format(data):
'''
Convert the API format for assignment and assignment templates to the data
format stored in the database.
'''
for unit in data.get('units', []):
if 'lists' in unit:
lists = unit['lists']
del unit['lists']
unit['listIds'] = map(lambda l: l['id'], lists)
if 'class' in data:
class_id = data['class']['id']
del data['class']
data['classId'] = class_id
class ListsHandler(OpenMindsAPIHandler):
'''
Handler for retrieving basic information about lists and creating
new lists.
'''
@add_cors_headers
@public_api_auth
def GET(self, auth_user=None, auth_app_id=None):
'''
Returns a JSON array of basic information about lists created
by the authenticated user.
'''
params = web.input(
search=None, num=50, grade=None, standard=None, section=None)
try:
item_lists = get_lists(auth_user, params)