Skip to content
Snippets Groups Projects
Commit 3bbe2b7c authored by Christopher Bohn's avatar Christopher Bohn :thinking:
Browse files

Create class wrappers for Canvas concepts.

Besides facilitating a more OO approach, the wrapper will make code
completion in IDEs possible.
parent 288f94ae
No related branches found
No related tags found
No related merge requests found
from canvasapi import Canvas
from config import Config
class CanvasSession:
__instance = None
@staticmethod
def get_session():
if CanvasSession.__instance is None:
CanvasSession.__instance = Canvas(Config.canvas_url, Config.canvas_api_key)
return CanvasSession.__instance
class CanvasUser:
def __init__(self, user):
super().__init__()
self.canvas_user = user
def get_name(self):
return self.canvas_user.name
def get_sortable_name(self):
return self.canvas_user.sortable_name
def get_username(self):
return self.canvas_user.login_id
def get_canvas_id(self):
return self.canvas_user.id
def get_nuid(self):
return self.canvas_user.sis_user_id
def get_email(self):
return self.canvas_user.email
def __repr__(self):
username = self.get_username()
return f'@{username}'
"""
// A Canvas user, e.g. a student, teacher, administrator, observer, etc.
{
// The ID of the user.
"id": 2,
// The name of the user.
"name": "Sheldon Cooper",
// The name of the user that is should be used for sorting groups of users, such
// as in the gradebook.
"sortable_name": "Cooper, Sheldon",
// A short name the user has selected, for use in conversations or other less
// formal places through the site.
"short_name": "Shelly",
// The SIS ID associated with the user. This field is only included if the user
// came from a SIS import and has permissions to view SIS information.
"sis_user_id": "SHEL93921",
// The id of the SIS import. This field is only included if the user came from
// a SIS import and has permissions to manage SIS information.
"sis_import_id": 18,
// The integration_id associated with the user. This field is only included if
// the user came from a SIS import and has permissions to view SIS information.
"integration_id": "ABC59802",
// The unique login id for the user. This is what the user uses to log in to
// Canvas.
"login_id": "sheldon@caltech.example.com",
// If avatars are enabled, this field will be included and contain a url to
// retrieve the user's avatar.
"avatar_url": "https://en.gravatar.com/avatar/d8cb8c8cd40ddf0cd05241443a591868?s=80&r=g",
// Optional: This field can be requested with certain API calls, and will return
// a list of the users active enrollments. See the List enrollments API for more
// details about the format of these records.
"enrollments": null,
// Optional: This field can be requested with certain API calls, and will return
// the users primary email address.
"email": "sheldon@caltech.example.com",
// Optional: This field can be requested with certain API calls, and will return
// the users locale in RFC 5646 format.
"locale": "tlh",
// Optional: This field is only returned in certain API calls, and will return a
// timestamp representing the last time the user logged in to canvas.
"last_login": "2012-05-30T17:45:25Z",
// Optional: This field is only returned in certain API calls, and will return
// the IANA time zone name of the user's preferred timezone.
"time_zone": "America/Denver",
// Optional: The user's bio.
"bio": "I like the Muppets."
}
"""
class GroupSet: # aka, group_category
def __init__(self, group_category):
super().__init__()
self.canvas_group_category = group_category
def get_name(self):
return self.canvas_group_category.name
def get_groups(self):
canvas_groups = self.canvas_group_category.get_groups()
groups = []
for group in canvas_groups:
groups.append(Group(group))
return groups
def create_group(self, group_name):
canvas_group = self.canvas_group_category.create_group(name=group_name)
return Group(canvas_group)
def create_groups(self, number_of_groups):
base_name = self.get_name()
groups = []
for group_number in range(1, number_of_groups+1):
canvas_group = self.create_group(f'{base_name} {group_number}')
groups.append(Group(canvas_group))
return groups
"""
{
// The ID of the group category.
"id": 17,
// The display name of the group category.
"name": "Math Groups",
// Certain types of group categories have special role designations. Currently,
// these include: 'communities', 'student_organized', and 'imported'. Regular
// course/account group categories have a role of null.
"role": "communities",
// If the group category allows users to join a group themselves, thought they
// may only be a member of one group per group category at a time. Values
// include 'restricted', 'enabled', and null 'enabled' allows students to assign
// themselves to a group 'restricted' restricts them to only joining a group in
// their section null disallows students from joining groups
"self_signup": null,
// Gives instructors the ability to automatically have group leaders assigned.
// Values include 'random', 'first', and null; 'random' picks a student from the
// group at random as the leader, 'first' sets the first student to be assigned
// to the group as the leader
"auto_leader": null,
// The course or account that the category group belongs to. The pattern here is
// that whatever the context_type is, there will be an _id field named after
// that type. So if instead context_type was 'Course', the course_id field would
// be replaced by an course_id field.
"context_type": "Account",
"account_id": 3,
// If self-signup is enabled, group_limit can be set to cap the number of users
// in each group. If null, there is no limit.
"group_limit": null,
// The SIS identifier for the group category. This field is only included if the
// user has permission to manage or view SIS information.
"sis_group_category_id": null,
// The unique identifier for the SIS import. This field is only included if the
// user has permission to manage SIS information.
"sis_import_id": null,
// If the group category has not yet finished a randomly student assignment
// request, a progress object will be attached, which will contain information
// related to the progress of the assignment request. Refer to the Progress API
// for more information
"progress": null
}
"""
class Group:
def __init__(self, group):
super().__init__()
self.canvas_group = group
def get_name(self):
return self.canvas_group.name
def get_number_of_students(self):
return self.canvas_group.members_count
def get_students(self):
canvas_users = self.canvas_group.get_users()
students = []
for student in canvas_users:
students.append(CanvasUser(student))
return students
def add_student(self, user):
self.canvas_group.create_membership(user.get_canvas_id())
"""
{
// The ID of the group.
"id": 17,
// The display name of the group.
"name": "Math Group 1",
// A description of the group. This is plain text.
"description": null,
// Whether or not the group is public. Currently only community groups can be
// made public. Also, once a group has been set to public, it cannot be changed
// back to private.
"is_public": false,
// Whether or not the current user is following this group.
"followed_by_user": false,
// How people are allowed to join the group. For all groups except for
// community groups, the user must share the group's parent course or account.
// For student organized or community groups, where a user can be a member of as
// many or few as they want, the applicable levels are
// 'parent_context_auto_join', 'parent_context_request', and 'invitation_only'.
// For class groups, where students are divided up and should only be part of
// one group of the category, this value will always be 'invitation_only', and
// is not relevant. * If 'parent_context_auto_join', anyone can join and will be
// automatically accepted. * If 'parent_context_request', anyone can request to
// join, which must be approved by a group moderator. * If 'invitation_only',
// only those how have received an invitation my join the group, by accepting
// that invitation.
"join_level": "invitation_only",
// The number of members currently in the group
"members_count": 0,
// The url of the group's avatar
"avatar_url": "https://<canvas>/files/avatar_image.png",
// The course or account that the group belongs to. The pattern here is that
// whatever the context_type is, there will be an _id field named after that
// type. So if instead context_type was 'account', the course_id field would be
// replaced by an account_id field.
"context_type": "Course",
"course_id": 3,
// Certain types of groups have special role designations. Currently, these
// include: 'communities', 'student_organized', and 'imported'. Regular
// course/account groups have a role of null.
"role": null,
// The ID of the group's category.
"group_category_id": 4,
// The SIS ID of the group. Only included if the user has permission to view SIS
// information.
"sis_group_id": "group4a",
// The id of the SIS import if created through SIS. Only included if the user
// has permission to manage SIS information.
"sis_import_id": 14,
// the storage quota for the group, in megabytes
"storage_quota_mb": 50,
// optional: the permissions the user has for the group. returned only for a
// single group and include[]=permissions
"permissions": {"create_discussion_topic":true,"create_announcement":true}
}
"""
class Course:
def __init__(self, course_id):
self.canvas_course = CanvasSession.get_session().get_course(course_id)
def get_all_users(self):
canvas_users = self.canvas_course.get_users()
users = []
for user in canvas_users:
users.append(CanvasUser(user))
return users
def get_students(self):
canvas_users = self.canvas_course.get_users(enrollment_type=['student'])
students = []
for user in canvas_users:
students.append(CanvasUser(user))
return students
def get_instructional_team(self):
canvas_users = self.canvas_course.get_users(enrollment_type=['teacher', 'ta'])
instructors = []
for user in canvas_users:
instructors.append(CanvasUser(user))
return instructors
def get_all_groups(self):
canvas_groups = self.canvas_course.get_groups()
groups = []
for group in canvas_groups:
groups.append(Group(group))
return groups
def get_group_sets(self):
canvas_group_categories = self.canvas_course.get_group_categories()
group_sets = []
for group_category in canvas_group_categories:
group_sets.append(GroupSet(group_category))
return group_sets
def create_groupset(self, groupset_name):
group_category = self.canvas_course.create_group_category(groupset_name)
return GroupSet(group_category)
"""
{
// the unique identifier for the course
"id": 370663,
// the SIS identifier for the course, if defined. This field is only included if
// the user has permission to view SIS information.
"sis_course_id": null,
// the UUID of the course
"uuid": "WvAHhY5FINzq5IyRIJybGeiXyFkG3SqHUPb7jZY5",
// the integration identifier for the course, if defined. This field is only
// included if the user has permission to view SIS information.
"integration_id": null,
// the unique identifier for the SIS import. This field is only included if the
// user has permission to manage SIS information.
"sis_import_id": 34,
// the full name of the course
"name": "InstructureCon 2012",
// the course code
"course_code": "INSTCON12",
// the current state of the course one of 'unpublished', 'available',
// 'completed', or 'deleted'
"workflow_state": "available",
// the account associated with the course
"account_id": 81259,
// the root account associated with the course
"root_account_id": 81259,
// the enrollment term associated with the course
"enrollment_term_id": 34,
// the grading standard associated with the course
"grading_standard_id": 25,
// the grade_passback_setting set on the course
"grade_passback_setting": "nightly_sync",
// the date the course was created.
"created_at": "2012-05-01T00:00:00-06:00",
// the start date for the course, if applicable
"start_at": "2012-06-01T00:00:00-06:00",
// the end date for the course, if applicable
"end_at": "2012-09-01T00:00:00-06:00",
// the course-set locale, if applicable
"locale": "en",
// A list of enrollments linking the current user to the course. for student
// enrollments, grading information may be included if include[]=total_scores
"enrollments": null,
// optional: the total number of active and invited students in the course
"total_students": 32,
// course calendar
"calendar": null,
// the type of page that users will see when they first visit the course -
// 'feed': Recent Activity Dashboard - 'wiki': Wiki Front Page - 'modules':
// Course Modules/Sections Page - 'assignments': Course Assignments List -
// 'syllabus': Course Syllabus Page other types may be added in the future
"default_view": "feed",
// optional: user-generated HTML for the course syllabus
"syllabus_body": "<p>syllabus html goes here</p>",
// optional: the number of submissions needing grading returned only if the
// current user has grading rights and include[]=needs_grading_count
"needs_grading_count": 17,
// optional: the enrollment term object for the course returned only if
// include[]=term
"term": null,
// optional: information on progress through the course returned only if
// include[]=course_progress
"course_progress": null,
// weight final grade based on assignment group percentages
"apply_assignment_group_weights": true,
// optional: the permissions the user has for the course. returned only for a
// single course and include[]=permissions
"permissions": {"create_discussion_topic":true,"create_announcement":true},
"is_public": true,
"is_public_to_auth_users": true,
"public_syllabus": true,
"public_syllabus_to_auth": true,
// optional: the public description of the course
"public_description": "Come one, come all to InstructureCon 2012!",
"storage_quota_mb": 5,
"storage_quota_used_mb": 5,
"hide_final_grades": false,
"license": "Creative Commons",
"allow_student_assignment_edits": false,
"allow_wiki_comments": false,
"allow_student_forum_attachments": false,
"open_enrollment": true,
"self_enrollment": false,
"restrict_enrollments_to_course_dates": false,
"course_format": "online",
// optional: this will be true if this user is currently prevented from viewing
// the course because of date restriction settings
"access_restricted_by_date": false,
// The course's IANA time zone name.
"time_zone": "America/Denver",
// optional: whether the course is set as a Blueprint Course (blueprint fields
// require the Blueprint Courses feature)
"blueprint": true,
// optional: Set of restrictions applied to all locked course objects
"blueprint_restrictions": {"content":true,"points":true,"due_dates":false,"availability_dates":false},
// optional: Sets of restrictions differentiated by object type applied to
// locked course objects
"blueprint_restrictions_by_object_type": {"assignment":{"content":true,"points":true},"wiki_page":{"content":true}}
}
"""
if __name__ == '__main__':
pass
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment