-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvas.py
1804 lines (1511 loc) · 66.3 KB
/
canvas.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
"""
A module for interacting with Instructure Canvas
Global parameters (most can also be changed on individual function calls):
base_url: string, containing the base url of canvas server
token: string, containing the user access token.
this_year: current year, for making class schedules
"""
from os.path import expanduser, getsize, basename
import requests
import arrow
import markdown
HAS_PANDOC = True
try:
import pypandoc
except ImportError:
HAS_PANDOC = False
base_url = "https://svsu.instructure.com/"
token = 'An invalid token. Redefine with your own'
this_year = int(arrow.now().format('YYYY'))
def read_access_token(file='~/.canvas/access_token'):
"Read access token if available"
global token
try:
with open(expanduser(file), 'r') as f:
token = f.read().rstrip('\n')
except:
print("Could not read access token")
# The main purpose for this is that we cannot splat things into a dict :(
def calendar_event_data(course, title, description, start_at, end_at):
"""
Creates a dict with parameters for calendar event data to be passed to
`create_calendar_event`. Parameters:
course: course id, string or int
title: string, event title
description: string, detailed event description
start_at: starting time, in YYYY-MM-DDTHH:MMZZ format
end_at: ending time, in YYYY-MM-DDTHH:MMZZ format
"""
event_data = {
'calendar_event[context_code]': 'course_{}'.format(course),
'calendar_event[title]': title,
'calendar_event[description]': description,
'calendar_event[start_at]': start_at,
'calendar_event[end_at]': end_at,
}
return event_data
def get_all_pages(orig_url, params=None):
"""
Auxiliary function that uses the 'next' links returned from the server to
request additional pages and combine them together into one json response.
Parameters:
orig_url: the url for the original request
params: a dict with the parameters for the original request (must
contain access token)
Returns:
A combined list of json results returned in all pages.
Warning:
Does not handle failure in any way! Make sure you don't kill your pets
by accident.
"""
url = orig_url
json = []
if params is None:
params = {}
while True:
resp = requests.get(url, params=params)
json += resp.json()
if 'next' not in resp.links:
return json
url = resp.links['next']['url']
params = {'access_token': params['access_token']}
def contact_server(contact_function, location, data=None, base=None,
access_token=None):
"""
Abstracting a server request. Builds a url from base and location, adds
access_token if given, or default token, to data dict, and calls
contact_function with the url and data. Returns the result of the
contact_function.
Also accepts a list of pairs as data.
"""
if data is None:
params = dict()
else:
params = data.copy() # prevent them from being clobbered
if isinstance(params, dict):
params['access_token'] = (
token if access_token is None
else access_token)
else:
params += [('access_token',
token if access_token is None
else access_token)]
return contact_function((base_url if base is None else base) + location,
params=params)
def progress(prog_url, access_token=None):
"""
Iterator that repeatedly checks progress from the given url. It yields the
json results of the progress query. It stops when workflow state is no
longer queued nor running.
"""
while True:
resp = requests.get(prog_url,
data={'access_token': token if access_token is None
else access_token})
resp.raise_for_status()
json = resp.json()
yield json
status = json['workflow_state']
if status != 'queued' and status != 'running':
break
def create_calendar_event(event_data, base=None, access_token=None):
"Post an event described by `event_data` dict to a calendar"
return contact_server(requests.post, 'api/v1/calendar_events.json',
event_data, base, access_token)
def list_calendar_events_between_dates(course, start_date, end_date, base=None,
access_token=None):
"""Lists all events in a given course between two dates.
Parameters:
course: course ID
start_date: start date in YYYY-MM-DD format
end_date: end date in YYYY-MM-DD format
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a list of json descriptions of events.
"""
return contact_server(get_all_pages, 'api/v1/calendar_events.json',
{
'type': 'event',
'start_date': start_date,
'end_date': end_date,
'context_codes[]': 'course_{}'.format(course),
},
base, access_token)
def list_calendar_events_all(course, base=None, access_token=None):
"""Lists all events in a given course.
Parameters:
course: course ID
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
"""
return contact_server(get_all_pages, 'api/v1/calendar_events.json',
{
'type': 'event',
'all_events': True,
'context_codes[]': 'course_{}'.format(course),
},
base, access_token)
def delete_event(event_id, base=None, access_token=None):
"""Deletes an event, specified by 'event_id'. Returns the event."""
return contact_server(requests.delete,
'api/v1/calendar_events/{}'.format(event_id),
{
'cancel_reason': 'no reason',
'access_token': access_token
},
base, access_token)
def class_span(start, length):
"""Returns class starting and ending time in isoformat. To be used with
`calendar_event_data`. Parameters:
start: an arrow object describing class starting time
length: length of class in minutes
"""
return start.isoformat(), start.replace(minutes=length).isoformat()
def firstclass(month, day, hour, minute, year=this_year):
"""
A convenience function creating an arrow object for the first class
in the semester
"""
return arrow.Arrow(year, month, day, hour, minute, 0, 0, 'local')
def create_events_from_list(course, event_list, start, length, base=None,
access_token=None):
"""
Creates a series of events for a MW or TR class. Parameters:
course: a course id, string or int
list: a list of events. A list of pairs, the first item in each is a
title, the second is a description. An empty string for title will
skip that day.
start: an arrow object describing the starting time of the first class.
Must be Monday or Tuesday!
length: int, length of class in minutes
"""
classtime = start
for i, event in enumerate(event_list):
if event[0] != "":
create_calendar_event(
calendar_event_data(course, event[0], event[1],
*class_span(classtime, length)),
base, access_token)
classtime = classtime.replace(days=2 if i % 2 == 0 else 5)
def convert_markdown(body, use_pandoc):
"""
Convert markdown string `body` to html. Use pandoc for conversion if
`use_pandoc` is true and pandoc is available.
"""
if use_pandoc and not HAS_PANDOC:
print("Warning: pypandoc not available! Trying builtin converter.")
print("Install pypandoc module to get rid of this error.")
use_pandoc = False
if use_pandoc:
return pypandoc.convert_text(body, "html", format="md",
extra_args=["--mathml"])
else:
return markdown.markdown(body, extensions=['extra'])
def upload_syllabus_from_markdown(course, markdown_body, access_token=None,
use_pandoc=False, base=None):
"""
Uploads syllabus body to a given course.
Parameters:
course: a course ID, int or string
markdown_body: the body of syllabus in markdown
use_pandoc: use Pandoc to convert markdown when available
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.put, 'api/v1/courses/{}'.format(course),
{'course[syllabus_body]':
convert_markdown(markdown_body, use_pandoc)
},
base, access_token)
def post_announcement_from_markdown(
course, title, markdown_body, use_pandoc=False,
access_token=None, base=None):
"""
Post an announcement to a given course
Parameters:
course: a course ID, int or string
title: the title of the announcement
markdown_body: the body of the announcement in markdown
use_pandoc: use Pandoc to convert markdown when available
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.post,
'api/v1/courses/{}/discussion_topics'.format(course),
{
'title': title,
'message': convert_markdown(markdown_body,
use_pandoc),
'is_announcement': '1'
},
base, access_token)
def post_group_announcement_from_markdown(
group, title, markdown_body, use_pandoc=False,
access_token=None, base=None):
"""
Post an announcement to a given group
Parameters:
group: a group ID, int or string
title: the title of the announcement
markdown_body: the body of the announcement in markdown
use_pandoc: use Pandoc to convert markdown when available
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.post,
'api/v1/groups/{}/discussion_topics'.format(group),
{
'title': title,
'message':
convert_markdown(markdown_body, use_pandoc),
'is_announcement': '1'
},
base, access_token)
def create_discussion(
course, title, markdown_message, discussion_type="threaded",
position_after=None,
published=True, allow_rating=False, sort_by_rating=False,
only_graders_can_rate=False,
podcast_enabled=False, podcast_student_posts=False,
require_initial_post=False, pinned=False, group=None,
use_pandoc=False,
access_token=None, base=None):
"""
Post a new discussion in a given course
Parameters:
course: a course ID, int or string
title: the title of the discussion
markdown_message: the message in markdown
discussion_type: threaded or side_comment
position_after: optional id of other discussion
published: should it be published
allow_rating: can post be rated
sort_by_rating: sort posts by rating
only_graders_can_rate: if true, only graders can rate (duh)
podcast_enabled: is there a podcast for the discussion
podcast_student_posts: include student posts in podcast
require_initial_post: do students have to post before commenting on
other posts
pinned: should the discussion be pinned
group: if set, the discussion will become a group discussion in a group
with this id
use_pandoc: use Pandoc to convert markdown when available
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.post,
'api/v1/courses/{}/discussion_topics'.format(course),
dict([
('title', title),
('message',
convert_markdown(markdown_message, use_pandoc)
),
('is_announcement', '0'),
('discussion_type', discussion_type),
('published', published),
('allow_rating', allow_rating),
('sort_by_rating', sort_by_rating),
('only_graders_can_rate', only_graders_can_rate),
('podcast_enabled', podcast_enabled),
('podcast_has_student_posts',
podcast_student_posts),
('require_initial_post', require_initial_post),
('pinned', pinned),
] +
([] if group is None else [('group', group)]) +
([] if position_after is None
else [('position_after', position_after)])
),
base, access_token)
def create_page_from_markdown(course, title, markdown_body, published=True,
use_pandoc=False, access_token=None, base=None):
"""
Creates a wiki page in a given course
Parameters:
course: a course ID, int or string
title: the title of the page
markdown_body: the body of page in markdown
published: if the page should be published
use_pandoc: use Pandoc to convert markdown when available
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.post,
'api/v1/courses/{}/pages'.format(course),
{
'wiki_page[title]': title,
'wiki_page[body]':
convert_markdown(markdown_body, use_pandoc),
'wiki_page[published]': '1' if published else '0'
},
base, access_token)
# The following function was provided by Mark A. Lilly (marqpdx):
def update_page_from_markdown(
course, title, markdown_body, url, published=True,
use_pandoc=False, access_token=None, base=None):
"""
updates a wiki page in a given course
Parameters:
course: a course ID, int or string
title: the title of the page
markdown_body: the body of page in markdown
url: the url of this page in the current course
published: if the page should be published
use_pandoc: use Pandoc to convert markdown when available
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.put,
'api/v1/courses/{}/pages/{}'.format(course, url),
{
'wiki_page[title]': title,
'wiki_page[body]':
convert_markdown(markdown_body, use_pandoc),
'wiki_page[published]': '1' if published else '0'
},
base, access_token)
def get_assignment_groups(course, access_token=None, base=None):
"""
Gets a list of all assignment groups for a course.
Parameters:
course: a course ID, int or string
access_token: access token
base: base url of canvas server
"""
return contact_server(get_all_pages,
'api/v1/courses/{}/assignment_groups'.format(course),
{'include[]': 'assignments'},
base, access_token)
def create_assignment_group(course, name, position=None, group_weight=0,
access_token=None, base=None):
"""
Create an assignment group in the course.
Parameters:
course: a course ID, int or string
name: the name of the group
position: position of the group on the group list
group_weight: relative weight of the group in grading, percent
access_token: access token
base: base url of canvas server
Currently does not allow setting grading rules. (TODO)
"""
return contact_server(requests.post,
'api/v1/courses/{}/assignment_groups'.format(course),
dict([
('name', name),
('group_weight', group_weight),
] +
([] if position is None
else [('position', position)])
),
base, access_token)
def delete_assignment_group(course, group_id, move_assignments_to=None,
access_token=None, base=None):
"""
Create an assignment group in the course.
Parameters:
course: a course ID, int or string
group_id: the id of the group, int or string
move_assignments_to: id of a group to move assignments to, if None,
the assignments will be deleted
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.delete,
'api/v1/courses/{}/assignment_groups/{}'
.format(course, group_id),
dict([] if move_assignments_to is None
else [('move_assignments_to',
move_assignments_to)]),
base, access_token)
def create_assignment(course, name, markdown_description, points, due_at,
group_id, submission_types="on_paper",
allowed_extensions=None, peer_reviews=False,
auto_peer_reviews=False, ext_tool_url=None,
ext_tool_new_tab=False,
access_token=None, base=None):
"""
Creates a simple assignment in the given course.
Parameters:
course: a course ID, int or string
name: the name of the assignment
markdown_description: description of the assignment, in markdown
points: max number of points for the assignment
due_at: due date for the assignment, in YYYY-MM-DDTHH:MM:SS
group_id: assignment group to place the assignment into
submission_types: how should it be submitted. Options are
"online_quiz", "none", "on_paper", "discussion_topic",
"external_tool", "online_upload", "online_text_entry",
"online_url", "media_recording"
allowed_extensions: if submission_types contains "online_upload", list
of allowed file extensions
peer_reviews: should the assignment be peer reviwed
auto_peer_reviews: assign reviewers automatically
ext_tool_url: url of external tool, is submission_types contains
"external_tool".
ext_tool_new_tab: Boolean, should external tool open in a new tab.
access_token: access token
base: base url of canvas server
"""
# The Canvas API documentation is wrong or at least misleading, submitting
# a hash for external_tool_assignment_tag causes internal server error. The
# fields have to he sent separately.
return contact_server(
requests.post,
'api/v1/courses/{}/assignments'.format(course),
dict([
('assignment[name]', name),
('assignment[description]',
markdown.markdown(markdown_description,
extensions=['extra'])),
('assignment[submission_types]',
submission_types),
('assignment[points_possible]', points),
('assignment[due_at]', due_at),
('assignment[assignment_group_id]', group_id),
('assignment[published]', 1),
('assignment[peer_reviews]', peer_reviews),
('assignment[automatic_peer_rewiews]',
auto_peer_reviews)
] +
([] if allowed_extensions is None
else [('assignment[allowed_extensions]',
allowed_extensions)]) +
([] if ext_tool_url is None
else [('assignment[external_tool_tag_attributes][url]',
ext_tool_url),
('assignment[external_tool_tag_attributes][new_tab]',
ext_tool_new_tab)])
),
base, access_token)
def course_settings_set(course, settings, access_token=None, base=None):
"""
Set settings in a course.
Parameters:
course: the course id
settings: a dict with course settings to change. Keys should be the
parts inside the square brackets of the parameter names for the
"Update a Course" API request
"""
return contact_server(
requests.put,
'api/v1/courses/{}'.format(course),
{
"course[{}]".format(k): v for k, v in settings.items()
},
base, access_token)
def create_redirect_tool(
course, text, url, new_tab=False, default=True,
access_token=None, base=None):
"""
Create a redirect tool for course navigation.
Parameters:
course: the course id
text: the text that will be displayed in the navigation
url: the redirection url
new_tab: should it open in a new tab?
default: should the tool be enabled by default
access_token: access token
base: base url of canvas server
"""
return contact_server(requests.post,
'api/v1/courses/{}/external_tools'.format(course),
{
'name': 'Redirect to ' + text,
'privacy_level': 'Anonymous',
'consumer_key': 'N/A',
'shared_secret': 'hjkl',
'url': 'https://www.edu-apps.org/redirect',
'text': text,
'custom_fields[url]': url,
'custom_fields[new_tab]': (1 if new_tab else 0),
'not_selectable': True,
'course_navigation[enabled]': True,
'course_navigation[text]': text,
'course_navigation[default]': default,
'description': "Redirects to " + url
},
base, access_token)
def list_files(course, pattern, folder=None,
access_token=None, base=None):
"""
Lists files matching pattern
Parameters:
course: the course id
pattern: the pattern to match
folder: currently unused
access_token: access token
base: base url of canvas server
"""
return contact_server(get_all_pages,
'api/v1/courses/{}/files'.format(course),
{'search_term': pattern},
base, access_token)
def upload_file_to_course(course, local_file, upload_path, remote_name=None,
content_type=None, overwrite=False,
access_token=None, base=None):
"""
Upload a file to the course 'files'.
Parameters:
course: the course id
local_file: the local path to the file. The file must exist, and not
be huge
upload_path: the remote directory the file goes to. It will be created
if it does not exist
remote_name: the file name to use on the server. When unspecified, it
will be extracted from `local_file`
content_type: mailcap style content type. Will be inferred from the
file extension if unspecified
overwrite: if True, overwrite existing file. Otherwise upload file
under a modified name
access_token: access token
base: base url of canvas server
"""
response = contact_server(
requests.post,
'api/v1/courses/{}/files'.format(course),
data=dict(
[
('name', remote_name if remote_name is not None
else basename(local_file)),
('size', getsize(local_file)),
('parent_folder_path', upload_path),
('on_duplicate', 'overwrite' if overwrite
else 'rename')
] + ([('content_type', content_type)]
if content_type is not None else [])),
base=base, access_token=access_token)
response.raise_for_status()
upload_url = response.json()["upload_url"]
upload_params = response.json()["upload_params"]
with open(local_file, 'rb') as file:
return requests.post(
upload_url, data=upload_params, files={'file': file})
def import_qti_quiz(course, qti_file, access_token=None, base=None):
"""
Upload a file to the course 'files'. This is specifically meant to upload
quizzes created by R/exams, namely `exams2canvas` function, so it is not as
flexible as it could be.
Parameters:
course: the course id
qti_file: the local path to the file. The file must exist, and not be
huge, and it must be a qti zipped file
access_token: access token
base: base url of canvas server
Returns:
Response with the migration info
"""
response = contact_server(requests.post,
'api/v1/courses/{}/content_migrations'.format(
course),
data=dict(
[
('migration_type', 'qti_converter'),
('pre_attachment[name]',
basename(qti_file)),
('pre_attachment[size]',
getsize(qti_file))
]),
base=base, access_token=access_token)
response.raise_for_status()
upload_url = response.json()['pre_attachment']['upload_url']
upload_params = response.json()['pre_attachment']['upload_params']
migration_id = response.json()['id']
with open(qti_file, 'rb') as file:
requests.post(upload_url, data=upload_params, files={'file': file})
return contact_server(requests.get,
"/api/v1/courses/{}/content_migrations/{}".format(
course, migration_id
))
def get_list_of_courses(access_token=None, base=None):
"""
Returns a list of current user's courses, as a list of json course data,
one record for each course.
Parameters:
access_token: access token
base: base url of canvas server
"""
return contact_server(get_all_pages, 'api/v1/courses', {},
base, access_token)
def get_students(course, base=None, access_token=None):
"""Lists all students in a given course.
Parameters:
course: course ID
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a list of dicts, one for each student
"""
return contact_server(get_all_pages,
'api/v1/courses/{}/users'.format(course),
{'enrollment_type': 'student'},
base, access_token)
def find_user_by_login_id(login_id, base=None, access_token=None):
"""Search for a user with a given sis_login_id, if found, return user
profile.
Parameters:
login_id: user's sis_login_id
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a request result
"""
return contact_server(requests.get,
"/api/v1/users/sis_login_id:{}/profile".format(
login_id),
base, access_token)
def enroll_user_by_login_id(course, login_id, base=None, access_token=None):
"""Enrolls a user with a given sis_login_id, if found. Returns user
profile.
Parameters:
course: course ID
login_id: user's sis_login_id
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a request result
"""
resp = find_user_by_login_id(login_id, base, access_token)
if resp.status_code != 200:
return resp
json = resp.json()
if "login_id" in json and json["login_id"] == login_id and "id" in json:
id = resp.json()['id']
else:
return resp
return contact_server(requests.post,
'api/v1/courses/{}/enrollments'.format(course),
{'enrollment[user_id]': id,
'enrollment[enrollment_state]': 'active'},
base, access_token)
def get_enrollments(course, base=None, access_token=None):
"""Lists all enrollments in a given course.
Parameters:
course: course ID
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a list of dicts, one for each enrollment
"""
return contact_server(get_all_pages,
'api/v1/courses/{}/enrollments'.format(course),
{},
base, access_token)
def enrollment_stop(
course, user_id, task="conclude", base=None, access_token=None):
"""Modifies an enrollment of given user in given course.
Parameters:
course: course ID
user_id: user id (numerical Canvas id)
task: how should the enrollment change?
"conclude", "delete", "deactivate"
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a request result
"""
return contact_server(requests.delete,
'api/v1/courses/{}/enrollments/{}'.format(
course, user_id),
{"task": task},
base, access_token)
def create_appointment_group(course_list, title, description, location,
time_slots, publish=False, max_part=None,
min_per_part=None, max_per_part=1, private=True,
base=None, access_token=None):
"""
Create an appointment group.
Parameters:
course_list: a list of course ids. Students in those courses
will be allowed to sign up
title: a title of the group
description: a description
location: a string, location of the appointment
time_slots: a list of pairs of times - (start, end) for each
slot
publish: publish right away or wait (can't be unpublished)
max_part: maximum number of participants per appointment (default
no limit)
min_per_part: minimum number of appointment a participant must sign
up for (default no minimum)
max_per_part: maximum number of appointment a participant must sign
up for (default unknown, we set it to 1)
private: participants cannot see each others names
"""
return contact_server(
requests.post, "/api/v1/appointment_groups",
dict([
('appointment_group[context_codes][]',
['course_{}'.format(id) for id in course_list]),
('appointment_group[title]', title),
('appointment_group[description]', description),
('appointment_group[location_name]', location),
('appointment_group[participants_per_appointment]',
max_part),
('appointment_group[max_appointments_per_participant]',
max_per_part),
('appointment_group[min_appointments_per_participant]',
min_per_part),
('appointment_group[participant_visibility]',
'private' if private else 'protected'),
('appointment_group[publish]', publish)] +
[('appointment_group[new_appointments][{}][]'.format(i+1),
slot) for i, slot in enumerate(time_slots)]
),
base, access_token)
def get_group_categories(course, base=None, access_token=None):
"""Lists all group categories in a given course.
Parameters:
course: course ID
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a list of dicts, one for each category
"""
return contact_server(get_all_pages,
'api/v1/courses/{}/group_categories'.format(course),
base, access_token)
def get_groups(course, category=None, base=None, access_token=None):
"""
Lists groups in a course. If category ID is given, only list the groups
in this category. Note that in that case, course id is ignored.
Parameters:
course: course ID
category: optional string or int, an ID of a group category.
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a list of dicts, one for each group.
"""
if category is None:
api = 'api/v1/courses/{}/groups'.format(course)
else:
api = 'api/v1/group_categories/{}/groups'.format(category)
return contact_server(get_all_pages,
api,
base, access_token)
def get_group_members(group, base=None, access_token=None):
"""
Get a list of all members of a group"
Parameters:
group: group ID
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns:
a list of users
"""
return contact_server(get_all_pages,
"/api/v1/groups/{}/users".format(group),
base, access_token)
def get_assignments(course, search=None, bucket=None, base=None,
access_token=None):
"""
Get a list of assignments for a course.
Parameters:
course: course ID
search: an optional search term for assignment names
bucket: optional, if included, only return certain assignments
depending on due date and submission status. Valid buckets are
“past”, “overdue”, “undated”, “ungraded”, “upcoming”,
and “future”.,
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns:
list of assignments
"""
return contact_server(
get_all_pages,
"/api/v1/courses/{}/assignments".format(course),
None if (search is None and bucket is None) else
dict(([] if search is None else [('search_term', search)]) +
([] if bucket is None else [('bucket', bucket)])),
base, access_token)
def get_submissions(course, assignment=None, student=None, assignments=None,
students=None, grouped=True, base=None, access_token=None):
"""
Get assignment(s) submission(s) from the course.
Parameters:
course: course ID
assignment: an assignment ID, if a single assignment is to be obtained
student: a student id, if a single students' assignments should be
obtained
assignments: a list of assignment ids. If both assignment and
assignments are None, obtain all assignments
students: a list of student ids. If both student and students are None,
obtain assignments for all students
grouped: If multiple assignments for multiple students are to be
listed, should they be grouped by students? Otherwise ignored.
base: optional string, containing the base url of canvas server
access_token: optional access token, if different from global one
Returns a list of submissions.
"""
data = None
if student is None:
if assignment is None:
data = dict(
[('student_ids[]',
"all" if students is None else ','.join(str(id) for id
in students))] +
([] if assignments is None else ['assignments_ids[]',
','.join(str(id) for id in
assignments)]) +
[('grouped', 1 if grouped else 0)])
api = "/api/v1/courses/{}/students/submissions".format(course)
else:
api = "/api/v1/courses/{}/assignments/{}/submissions".format(
course, assignment)
else:
api = "/api/v1/courses/{}/assignments/{}/submissions/{}".format(
course, assignment, student)
return contact_server(get_all_pages, api, data, base, access_token)
def create_grade_data(grades, assignment_id=None):
"""
A help function that takes an assignment id and a dict of student